Java Interview Question

Use this advanced question and answer to prepare for your next Java interview.

Explain why Java is Pass-by-Value and not Pass-by-Reference. Give an example.


Pass-by-value is when the reference to an object is copied to a new variable.

Pass-by-reference is when a reference to an object is passed directly to the other method.

When a method is called in Java, new Stack space is allocated for the method and all variables in the arguments are copied to the new Stack block.

Example:

private void A() {
  Something s = new Something();
  s.setMe("S");
  System.out.println(s.getMe());
  B(s);
  System.out.println(s.getMe());
}

private void B(Something x) {
  x.setMe("X");
  x = new Something();
  x.setMe("Y");
}

In the first print statement, S is printed. In the second print statement, X is printed. This is because the variable x is local to B and the variable s is local to A. Before x is initialized to a new object, both x and s are pointing to the same object on the Heap, but they are individual references. Changing the object to which x points will not change the object to which s points.

In a pass-by-reference language, the second print statement would print Y.

Looking for developers?