Easy java core-java

Is Java pass-by-value or pass-by-reference?

The 30 second answer

Java is always pass-by-value. For a primitive, the method gets a copy of the value. For an object, the method gets a copy of the reference, so it can change the object's contents through it, but if it points the parameter at a new object, the caller doesn't see that. So mutating a list inside a method is visible outside; reassigning the parameter is not.

<!-- level: 1 --> <!-- must_know: true -->

static void inc(int x) { x++; }
static void reassign(StringBuilder sb) { sb = new StringBuilder("new"); }
static void mutate(StringBuilder sb) { sb.append(" changed"); }

int x = 5;               inc(x);       // x is still 5
StringBuilder sb = new StringBuilder("old");
reassign(sb);                          // sb is still "old"
mutate(sb);                            // sb is now "old changed"

Output on Java 21: x 5, after reassign old, after mutate old changed.

The Java tutorial states that primitive arguments are passed by value, and that "Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before." The object's fields can still be changed if the method has the right access.

Sources (1)
  1. Java tutorial: Passing information to a method or a constructordocs.oracle.com