Java Pass-by-Value, Returning Objects and Autoboxing (OCP 21)
How Java passes data into and out of methods for the OCP 21 exam: pass-by-value for primitives and references, mutating versus reassigning a parameter, ignored return values, and autoboxing and unboxing rules, including the no-widen-then-box limit, null unboxing and the Integer cache.
kvi5hnuCode Sprout team member8 min readOn this page
When you call a method, how does the data get in, and what does the caller see afterwards? Java has one rule, and it has no exceptions: arguments are passed by value. The method gets a copy of each argument's value. The confusing part is that for objects, the value being copied is a reference. This article covers that rule, how data comes back through return values, and how Java converts automatically between primitives and their wrapper classes (autoboxing and unboxing).
Pass-by-value with primitives
public static void main(String[] args) {
int score = 40;
reset(score);
System.out.println(score); // 40
}
static void reset(int score) {
score = 99; // changes the method's copy only
}
The parameter score is a separate local variable that happens to have the same name, and the exam often reuses names to confuse you. Assigning to the parameter never affects the caller's variable.
The classic demonstration is a swap that doesn't swap:
static void swap(int a, int b) { int t = a; a = b; b = t; }
int x = 1, y = 2;
swap(x, y);
System.out.println(x + "," + y); // 1,2
Pass-by-value with references
For an object, the variable holds a reference, and the method gets a copy of that reference. The caller's variable and the parameter now point at the same object. Two things can happen inside the method, and they have opposite effects:

static void mutate(StringBuilder sb) {
sb.append(" (checked)"); // 1. changes the shared object: the caller sees it
sb = new StringBuilder("other"); // 2. points the copy elsewhere: the caller doesn't see it
sb.append(" ignored"); // changes the new object only
}
var note = new StringBuilder("Mira");
mutate(note);
System.out.println(note); // Mira (checked)
- Calling a method on the parameter (
append,add,set,arr[i] = …) changes the object both variables share, so the caller sees the change. - Assigning to the parameter (
sb = …) changes only the method's copy of the reference. The caller's variable still points at the original object.
That's why swapping the contents of an array works when swapping two int parameters doesn't:
static void swap(int[] p) { int t = p[0]; p[0] = p[1]; p[1] = t; }
int[] pair = {1, 2};
swap(pair); // pair is now {2, 1}
Strings look like the primitive case
static void rename(String name) { name = name + " Jr."; }
String name = "Mira";
rename(name);
System.out.println(name); // Mira
String is immutable, so there's no method that changes the original object. name + " Jr." creates a new String, and the assignment only changes the parameter. The same applies to the wrapper classes such as Integer, which are immutable too.
Returning data
A method sends data back with return. The caller gets a copy of the primitive value or of the reference. The returned value is only useful if the caller does something with it:
static int addBonus(int score) { score += 10; return score; }
static String addSuffix(String s) { s += "!"; return s; }
int score = 40;
String tag = "go";
addBonus(score); // result ignored: score is still 40
tag = addSuffix(tag); // result stored: tag is now "go!"
System.out.println(score + tag); // 40go!
When a question passes data around between several methods, write down the value of each variable after every line. Look for return values that are thrown away, and for parameters that are reassigned instead of mutated.
Autoboxing and unboxing
Each primitive type has a wrapper class: Boolean, Byte, Short, Character, Integer, Long, Float and Double. You can convert between them by hand:
int n = 5;
Integer boxed = Integer.valueOf(n); // primitive → wrapper
int back = boxed.intValue(); // wrapper → primitive
Since Java 5, the compiler does this for you:
- Autoboxing converts a primitive into its wrapper.
- Unboxing converts a wrapper into its primitive.
Integer boxed = 5; // autoboxing
int back = boxed; // unboxing
Character letter = 'p'; // autoboxing
char c = letter; // unboxing
Boolean flag = true; // autoboxing
long widened = boxed; // unbox to int, then widen to long: allowed
List<Integer> temps = new ArrayList<>();
temps.add(21); // autoboxed to Integer
int first = temps.get(0); // unboxed
Arithmetic and comparisons on wrappers unbox them first. boxed + 1 is an int, and boxed++ unboxes the value, adds one and boxes a new Integer. Other variables that referred to the old object don't change.
The limit: Java won't widen and box in one step
The compiler will widen a primitive (int → long) or box it (int → Integer), but not both in one conversion:
Long a = 8; // DOES NOT COMPILE: int can't become Long
Long b = 8L; // fine: long → Long
Double d = 1; // DOES NOT COMPILE: int can't become Double
Double e = 1.0; // fine
Integer i = 3;
Long f = i; // DOES NOT COMPILE: Integer and Long are unrelated classes
long g = i; // fine: unbox, THEN widen (the allowed order)
The reverse order, unboxing and then widening, is allowed, which is why long g = i compiles.
One assignment-only special case: a constant int that fits in the type can be narrowed and boxed, so Short s = 8;, Byte b = 1; and Character c = 65; all compile. This works only for assignments of constant expressions, not for method arguments, as you'll see below.
The same rules apply in array initializers:
Integer[] hours = {9, 12}; // fine
Double[] temps = {18.5, 21.0}; // fine
Integer[] bad1 = {10.5}; // DOES NOT COMPILE
Double[] bad2 = {9, 21}; // DOES NOT COMPILE: int can't become Double
Boxing in method calls
Arguments are converted like assignments, but without the constant-narrowing special case:
void climb(long t) {}
void swing(Integer u) {}
void rest(Long x) {}
void sit(Short s) {}
void jump(int v) {}
climb(123); // fine: int widens to long
swing(123); // fine: int boxes to Integer
rest(8); // DOES NOT COMPILE: would need widen + box
sit(8); // DOES NOT COMPILE: no constant narrowing for arguments
jump(123L); // DOES NOT COMPILE: long → int is narrowing
A boxed value can also be passed to a supertype of its wrapper: void any(Object o) and void num(Number n) both accept 5, which is boxed to Integer. Article 30 shows the order Java tries these conversions in when several overloads could match.
Unboxing null
A wrapper variable can be null, but a primitive can't. Unboxing null throws a NullPointerException:
Integer missing = null;
int n = missing; // NullPointerException at run time
Character c = null;
char ch = c; // NullPointerException
The code compiles, so watch for it in "what is the result" questions, especially with collections that contain null or Map.get calls that return null for a missing key.
== on wrappers
== compares references when both operands are wrapper objects. Integer.valueOf (which autoboxing uses) caches the values from -128 to 127, so small values often share an object, and larger ones usually don't:
Integer a = 100, b = 100;
Integer c = 1000, d = 1000;
System.out.println(a == b); // true (cached object)
System.out.println(c == d); // false (two objects, with the default cache size)
System.out.println(c.equals(d)); // true
System.out.println(c == 1000); // true: one operand is primitive, so c is unboxed
Always use equals to compare wrapper values.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- The wrapper constructors such as
new Integer(5)have been deprecated for removal since Java 16 (JEP 390). UsevalueOfor autoboxing. Project Valhalla may later turn wrappers into value classes, but that isn't part of any release up to Java 25.
Exam traps from this article
A complete example
The program passes primitives, Strings, StringBuilders, lists and arrays to methods that reassign or mutate their parameters, ignores one return value and uses another, and then shows boxing, unboxing, the immutability of Integer, the Integer cache and unboxing null.
import java.util.ArrayList;
import java.util.List;
public class Solution {
// Each method receives COPIES of the caller's values.
static void reassignPrimitive(int score) {
score = 99; // changes only the copy
}
static void reassignString(String name) {
name = name + " Jr."; // new String; the caller's variable is untouched
}
static void mutateBuilder(StringBuilder sb) {
sb.append(" (checked)"); // same object as the caller's
sb = new StringBuilder("replacement"); // now points elsewhere; the caller doesn't see it
sb.append(" ignored");
}
static void mutateList(List<String> items) {
items.add("tent"); // visible to the caller
items = new ArrayList<>(); // invisible to the caller
items.add("never seen");
}
static void swap(int a, int b) {
int t = a;
a = b;
b = t; // swaps the copies only
}
static void swap(int[] pair) {
int t = pair[0];
pair[0] = pair[1];
pair[1] = t; // swaps the shared array's contents
}
// Getting data out: return it, and remember to use the result.
static int addBonus(int score) {
return score + 10;
}
static double average(List<Integer> values) {
long sum = 0;
for (int v : values) { // unboxing Integer -> int on each element
sum += v;
}
return values.isEmpty() ? 0 : (double) sum / values.size();
}
static String describe(Object value) {
return value + " is a " + value.getClass().getSimpleName();
}
public static void main(String[] args) {
System.out.println("== Pass-by-value");
int score = 40;
String name = "Mira";
var note = new StringBuilder("Mira");
var gear = new ArrayList<>(List.of("rope"));
reassignPrimitive(score);
reassignString(name);
mutateBuilder(note);
mutateList(gear);
System.out.println(score + " | " + name + " | " + note + " | " + gear);
int x = 1, y = 2;
swap(x, y);
int[] pair = {1, 2};
swap(pair);
System.out.println("swap(int, int): " + x + "," + y + " swap(int[]): " + pair[0] + "," + pair[1]);
addBonus(score); // result ignored
System.out.println("ignored: " + score + ", used: " + addBonus(score));
System.out.println("\n== Autoboxing and unboxing");
Integer boxed = score; // autoboxing int -> Integer
int unboxed = boxed; // unboxing Integer -> int
long widened = boxed; // unbox, then widen to long
System.out.println(boxed + " " + unboxed + " " + widened);
System.out.println(describe(7) + ", " + describe(7L) + ", " + describe('7') + ", " + describe(7.0f));
List<Integer> temps = new ArrayList<>(List.of(18, 21, 24));
temps.add(19); // boxed automatically
System.out.println("average " + average(temps));
Integer before = boxed;
boxed++; // unbox, add, box a NEW Integer
System.out.println("after ++: " + boxed + ", old reference still " + before);
Integer small1 = 100, small2 = 100, big1 = 1000, big2 = 1000;
System.out.println("== on 100: " + (small1 == small2) + ", == on 1000: " + (big1 == big2)
+ ", equals on 1000: " + big1.equals(big2));
Integer missing = null;
try {
int crash = missing; // unboxing null
System.out.println(crash);
} catch (NullPointerException e) {
System.out.println("unboxing null -> NullPointerException");
}
}
}
Output:
== Pass-by-value
40 | Mira | Mira (checked) | [rope, tent]
swap(int, int): 1,2 swap(int[]): 2,1
ignored: 40, used: 50
== Autoboxing and unboxing
40 40 40
7 is a Integer, 7 is a Long, 7 is a Character, 7.0 is a Float
average 20.5
after ++: 41, old reference still 40
== on 100: true, == on 1000: false, equals on 1000: true
unboxing null -> NullPointerException
Points to notice:
- The first output line shows all four cases. The
intand theStringare unchanged, theStringBuilderand the list show the mutation, and neither shows the reassigned parameter. swap(int, int)changes nothing, whileswap(int[])swaps the shared array's contents.describe(7L)anddescribe('7')box toLongandCharacter, because each primitive boxes to its own wrapper.- After
boxed++,beforestill refers to the oldInteger40. The increment created a new object. == on 1000isfalsewith the default cache size, so compare wrapper values withequals.
Common questions
If Java is pass-by-value, why does my list change after I pass it to a method? The reference was copied, but both copies point at the same list. The method changed the list, not your variable.
Can a method make the caller's variable point at a new object?
Not directly. Return the new object and have the caller assign it, or wrap it in a holder object (an array, an AtomicReference, or a field of an object you pass in).
Does autoboxing hurt performance?
It allocates objects outside the cache range and adds indirection, which matters in tight loops over large data. Prefer primitive arrays or IntStream there. For normal code, the convenience is worth it.
Why does Character c = 65; compile but Character c = someInt; doesn't?
Constant narrowing only applies to compile-time constant expressions whose value fits the target. A non-constant int variable could hold any value, so the compiler rejects it.
Summary
- Java passes every argument by value. For an object, the value is a reference, so the caller and the method share the object but not the variable.
- Mutating a shared object is visible to the caller. Reassigning a parameter isn't.
- Return values are copies, and a call whose result isn't used has no effect on the caller's variables.
- Autoboxing and unboxing convert between primitives and wrappers automatically. Java won't widen and box in one step, but it will unbox and then widen.
- Unboxing
nullthrowsNullPointerException, and==on two wrappers compares references, so useequals.
Practice quiz
Test yourself with the pass-by-value and autoboxing quiz: 10 exam-style questions with explanations.
Previous: Java static Members, Static Initializers and Static Imports (OCP 21)
Next: Java Method Overloading and Overload Resolution (OCP 21)
Related reading
- Java static Members, Static Initializers and Static Imports (OCP 21)
- Java Access Modifiers: private, Package, protected and public (OCP 21)
- Java Local and Instance Variables, Effectively Final and Varargs (OCP 21)
- Java Method Declarations: Access Modifiers, Specifiers, Return Types and Parameters (OCP 21)
- Java Period, Duration, Instant and Daylight Saving Time (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.