Java Pass Values and Return Results
Java passes argument values into method parameters. When the value is an object reference, the caller and method may still reach the same mutable object.
Understand the idea
Reassigning a parameter does not reassign the caller’s variable. Mutating a shared object is different: the reference was copied, but the object was not cloned. Return a value when you want the caller to replace its local result explicitly. Keep parameter names and order clear because several parameters with the same type can be accidentally swapped without a compile error.
Run it locally
Use a local JDK 21 or newer. Save the complete example as Main.java in a separate lab folder, then compile and run it with the commands below. Java examples do not run in Bhylu’s browser playground. The -ea option enables assertion checks used by some lessons.
javac --release 21 -encoding UTF-8 -d out Main.java
java -ea -cp out MainA worked example
public class Main {
static int addOne(int value) { return value + 1; }
static void appendDay(StringBuilder value) { value.append(" Sunday"); }
public static void main(String[] args) {
int seats = 5;
System.out.println(addOne(seats));
System.out.println(seats);
StringBuilder label = new StringBuilder("Lab");
appendDay(label);
System.out.println(label);
}
}
Expected output
6
5
Lab SundayThe first helper returns a new primitive result while seats remains five. The second helper mutates the builder reached by the copied reference, so the caller observes the appended day. Neither call changes Java into a pass-by-reference language. The distinction is between copying a reference value and copying an object’s state.
Check the official Java documentation for detailed contracts and supported options.