Java Primitive Copy vs Reference Gotcha
Fast recall
Quick revision
Core answer
int b = a gives b its own copy of 5. Changing b to 10 has no effect on a; they are completely independent variables.Whether the candidate understands pass-by-value and the difference between primitives and objects in Java
Confusing this with object references where two variables can point to the same object
Contrast with object reference behavior — if a and b both referenced the same object, mutating via b would affect what a sees
Interview-ready guide
Interview answer
It prints `5` — and that's the whole point of the question. When you write int b = a, Java doesn't wire the two variables together; it reads the value in a, copies that number into a fresh slot for b, and walks away. So changing b to 10 touches only b — a was never connected, so it stays 5. It's like photocopying a page: scribbling on the copy never changes the original.
Where I'd show I actually understand it is the contrast with objects. If a and b were two references to the same ArrayList, then b = a would copy the arrow, not the list, and adding through b would show up through a. Primitives copy the value; reference variables copy the link — and that same rule is why passing an int into a method can't change the caller's variable, since the method just gets a copy. Java is always pass-by-value; for objects, the value being copied just happens to be the reference.
Java Primitive Copy vs Reference Gotcha
Direct Answer
It prints 5. Primitives in Java are copied by value — int b = a gives b its own copy of 5. Changing b to 10 has no effect on a; they are completely independent variables.
Code Example
Passing a primitive into a method is just another assignment — the parameter gets a copy. So a method can never change the caller's variable through the argument alone.
public class ValueCopyDemo {
public static void main(String[] args) {
int x = 100;
modify(x);
System.out.println(x); // still 100 — method got a copy
}
static void modify(int value) {
value = 999; // only the local copy changes
}
}
This is why a method that needs to hand a new value back must return it. Java is always pass-by-value — even for objects, what gets copied is the reference, not the object itself.
Common Mistakes & Pitfalls
- Expecting a link:
int b = a;doesn't connect the variables — they're separate. - Confusing with objects:
List<String> listB = listA;makes both point to the same list, so changes via one are visible through the other. - Thinking parameters are references: passing an
intand changing it inside doesn't affect the original — use areturn.
Check your understanding
Answer these without looking back at the article.
- Is Java pass-by-value or pass-by-reference?
- What happens when you assign one object reference to another?
- How does Java handle arrays — are they primitives or objects?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.