AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumjavacall by valuearrays

~90s

What a method can and cannot change

What does this Java program print?

public class Main {
    static void f(int[] a, int x) {
        a[0] = 99;
        x = 99;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2};
        int n = 1;
        f(arr, n);
        System.out.println(arr[0] + " " + n);
    }
}
Show the answer and the worked solution

Correct answer: C.

99 1

Worked solution

  1. The parameter a is a copy of the reference held in arr, so both names point at the same array object, and a[0] = 99 changes the object the caller can see.
  2. The parameter x is a copy of the int n, so x = 99 changes only that copy and n is still 1.
  3. The program therefore prints 99 1.

Answer: 99 1.

The idea

Java is call by value throughout; what varies is whether the value is a number or a reference. Writing through a reference is visible outside, reassigning the parameter never is.

Shortcut. Writing through a copied reference (a[0] = 99) reaches the caller's array; assigning to a copied int (x = 99) does not, so 99 1.

Common trap. "1 1" takes "Java is pass by value" to mean the array cannot change either; the copied value is a reference to the same array.

What a method can and cannot change — Aptitude Question

What a method can and cannot change: What does this Java program print? Answer and worked solution on CodeKairo.

Question

What does this Java program print?

public class Main {
    static void f(int[] a, int x) {
        a[0] = 99;
        x = 99;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2};
        int n = 1;
        f(arr, n);
        System.out.println(arr[0] + " " + n);
    }
}

Options

  1. 1 1
  2. 1 99
  3. 99 1
  4. 99 99
Show the answer and the worked solution

Correct answer: C. 99 1

Worked solution

  1. The parameter a is a copy of the reference held in arr, so both names point at the same array object, and a[0] = 99 changes the object the caller can see.
  2. The parameter x is a copy of the int n, so x = 99 changes only that copy and n is still 1.
  3. The program therefore prints 99 1.

Answer: 99 1.

The idea

Java is call by value throughout; what varies is whether the value is a number or a reference. Writing through a reference is visible outside, reassigning the parameter never is.

Shortcut. Writing through a copied reference (a[0] = 99) reaches the caller's array; assigning to a copied int (x = 99) does not, so 99 1.

Common trap. "1 1" takes "Java is pass by value" to mean the array cannot change either; the copied value is a reference to the same array.

All Programming Fundamentals questions · placement mock tests