class Ex1{ 2. public static void main(String args[]){ 3. int x = 10; 4. int y = new Ex1().change(x); 5. System.out.print(x+y); 6. } 7. int change(int x){ 8. x=12; 9. return x; 10. } 11. }
Can you please explain this entire code and what is happening?
Given code is 1. class Ex1{ 2. public static void main(String args[]){ 3. int x = 10; 4. int y = new Ex1().change(x); 5. System.out.print(x+y); 6. } 7. int change(int x){ 8. x=12; 9. return x; 10. } 11. } This code initializes variable x with value 10. Then calling function change with variable x. change() function changing the value of x to 12 and returning updated x value. As x is passed by value the value of x in main() function remains 10. So, It returns 12. Return value is getting stored in variable named y So, the final values of x and y in main() method is 10 and 12 respectively. Then main() prints the sum of x and y i.e 10+12 = 22 It prints 22. Output is 22
Get Answers For Free
Most questions answered within 1 hours.