Java OCA OCP Practice Question 1221

Question

What is the output of the following application?

package mypkg; //w  w  w. ja va2  s  .c o m
public class Main { 
        private int size; 
        public Main(int size) {this.size=size;} 
     ? 
        public static void sendHome(Main p, int newSize) { 
           p = new Main(newSize); 
           p.size = 4; 
        } 
        public static final void main(String... params) { 
           final Main v = new Main(3); 
           sendHome(v,7); 
           System.out.print(v.size); 
        } 
} 
  • A. 3
  • B. 4
  • C. 7
  • D. The code does not compile.


A.

Note

The code compiles without issue, so Option D is incorrect.

The key here is that Java uses pass by value to send object references to methods.

Since the Main reference p was reassigned in the first line of the sendHome() method, any changes to the p reference were made to a new object.

In other words, no changes in the sendHome() method affected the object that was passed in. Therefore, the value of size was the same before and after the method call, making the output 3 and Option A the correct answer.




PreviousNext

Related