OCA Java SE 8 Mock Exam Review - OCA Mock Question 2








Question

What is the output of the following code?

    public static void main(String args[]) {  
        String s = "string 1"; 
        int i = 5; 
        someMethod1(i); 
        System.out.println(i); 
        someMethod2(s); 
        System.out.println(s); 
    } 

    public static void someMethod1(int i) {  
        System.out.println(++i); 
    } 
    public static void someMethod2(String s) {  
        s = "string 2";  
        System.out.println(s); 
    } 
  1. 5 5 string 2 string 1
  2. 6 6 string 2 string 2
  3. 5 5 string 2 string 2
  4. 6 5 string 2 string 1




Answer



D

Note

i variable in the main is not modified since it is passed by value.

String is passed by reference, the local variable s was modified in the third method, not the one in the main method.

public class Main {
//from  w w w.j  a  v  a2 s.c  o m
  public static void main(String args[]) {
    String s = "string 1";
    int i = 5;
    someMethod1(i);
    System.out.println(i);
    someMethod2(s);
    System.out.println(s);
  }

  public static void someMethod1(int i) {
    System.out.println(++i);
  }

  public static void someMethod2(String s) {
    s = "string 2";
    System.out.println(s);
  }
}

The code above generates the following result.