Call by Value and Call by Reference in Java — Java Technical Interview Questions & Answers
Call by Value and Call by Reference in Java
Call by Value and Call by Reference in Java
- Java is call by value. For int, the method gets a copy. Changing the copy does not change the caller’s variable.
- For objects, the method gets a copy of the reference (the arrow). Both arrows point to the same object, so field changes are visible. If the method does obj = new Thing(), the caller’s arrow does not change.
- The trap is saying “Java is call by reference”. It is not. It is call by value — the value of the reference is copied.
- Let's take this on the board with one tiny Main class — no extra files. Output: Asha scored 72 then Pass. Real Main. Swap marks/name to show one idea from Call by Value and Call by Reference in Java. Start from main, go line by line, and stop at each print. That output is the proof for Call by Value and Call by Reference.
Technical Interview Tip: Say: Java is call by value. For objects the reference is copied, not the object.
Code Examples for Call by Value and Call by Reference in Java
Example
// Call
public class Main {
public static void main(String[] args) {
int marks = 72;
String name = "Asha";
System.out.println(name + " scored " + marks);
if (marks >= 40) System.out.println("Pass");
}
}Output: Asha scored 72 then Pass. Real Main. Swap marks/name to show one idea from Call by Value and Call by Reference in Java.
How to Explain Call by Value and Call by Reference in Java to an Interviewer
Is Java call by reference?
No Call by value
What is copied for objects?
The reference Not the object