Is Java Pass by Value or Pass by Reference?
40 min · Beginner
Java is always pass by value. When the argument is an object, the value that is copied is the reference, so a method can change the object but can never make the caller's variable point to a different object. That one sentence answers the question and every puzzle built on it.
Topics in this lesson
- Model answer: always pass by value
- Predict the output: changing a field vs reassigning
- Swap two Integers in a method: why it fails
- Arrays passed to methods: changes are visible
- The whiteboard explanation
Interview questions this lesson answers
- Is Java pass by value or pass by reference?
- What is pass by value?
- What is pass by reference, and does Java have it?
- What happens when you pass an
intto a method and change it inside? - If Java is pass by value, why can a method change my object?
- What happens if a method assigns a new object to its parameter?
- Why can't you write a swap method for two Integers in Java?
- Can a method swap two elements of an array?
- What happens if a method does
arr = new int[5];? - What happens when you pass a String and change it inside the method?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.