Java OCA OCP Practice Question 1418

Question

What is the output of the following application?

package mypkg; /*from  ww w . jav  a 2  s.  co  m*/
public class Main { 
  public int m(int length, String[] type) { 
     length++; 
     type[0] = "LONG"; 
     return length; 
  } 
  public static void main(String[] argv) { 
     final Main h = new Main(); 
     int length = 5; 
     String[] type = new String[1]; 
     length = h.m(length, type); 
     System.out.print(length+","+type[0]); 
  } 
} 
  • A. 5,LONG
  • B. 6,LONG
  • C. 5,null
  • D. 6,null
  • E. The code does not compile.
  • F. The code compiles but throws an exception at runtime.


B.

Note

The application compiles and runs without issue, so Options E and F are incorrect.

Java uses pass-by-value.

So even though the change to length in the first line of the m() method does not change the value in the main() method.

The value is later returned by the method and used to reassign the length value.

The result is that length is assigned a value of 6, due to it being returned by the method.

For the second parameter, while the String[] reference cannot be modified to impact the reference in the calling method, the data in it can be.

The value of the first element is set to LONG, resulting in an output of 6,LONG, making Option B the correct answer.




PreviousNext

Related