Question discussion

What is the output of the following Java program?public class Main { static void change(int[] a, int x, StringBuilder sb) { a[0] = 9; x = 9…

2167Medium DSSSB TGT Computer Science 0 replies

What is the output of the following Java program?

public class Main {
    static void change(int[] a, int x, StringBuilder sb) {
        a[0] = 9;
        x = 9;
        sb.append("X");
        sb = new StringBuilder("Y");
    }
    public static void main(String[] args) {
        int[] arr = {1};
        int n = 1;
        StringBuilder s = new StringBuilder("S");
        change(arr, n, s);
        System.out.println(arr[0] + " " + n + " " + s);
    }
}
  • A9 1 SX
  • B1 1 S
  • C9 9 SX
  • D9 1 Y
Correct answer: A

Explanation

Java passes references by value: the array element and the StringBuilder contents change through the copied references, but assigning to x or re-pointing sb inside the method does not affect the caller's variables.

Discussion 0

Nobody has replied yet. Start the discussion!