Call by Value and Call by Reference in Java And Its Misconception
Basics of SQL
12 Hrs. duration
12 Modules
2600+ Learners
Start Learning
Java is counted among the most used programming languages as it is easy to use, supports multiple platforms, and has features that are worth using. One of the basic paradigms in the Java language is how arguments are passed to Java methods. The terms “Call by Value” and “Call by Reference ” are the ones most asked in Java. However, there is often confusion about how Java handles argument passing and whether it supports both of these mechanisms.
In this article, we will provide details on the concepts associated with understanding where call by value is used, call by reference aspect within Java, how Java executes method calls, the boundaries between call by value and call by reference in Java, how Java manages primitive types and objects, and programming concerning a successful outcome.
What is Call by Value (Pass by Value)?
Call by value in Java describes the process of invoking a method with the value passed as an argument. Because the method operates on a copy of the data, any modifications made to the parameter inside the method do not affect the original variable outside the method. To put it another way, call by value sends a copy of the variable to the method, so that any changes are only reflected there and not in the main method.
Important Features of Call by Value:
The method receives a copy of the value only.
The argument itself is unaffected by modifications made to the parameter inside the method.
It is used to stop inadvertent changes to the original data.
Example:
public class MainExample {
public static void main(String[] args) {
int a = 6;
changeVal(a); // Passing a copy of a
System.out.println("After method call, a = " + a); // a remains unchanged
}
public static void changeVal(int n) {
n = n + 4; // Changes only the copy of a
}
}
Output:
After method call, a = 6
In this example, the value of ‘a’ is unchanged because only a copy of ‘a’ was passed to the changeVal() method.
Call by Reference or Pass by Reference is an argument passing technique where the method receives the address (reference) of the passed parameter. In this instance, modifications made to a parameter’s value inside the function also have an external impact. To put it another way, since the method uses the original variable’s reference (address), any changes made to a parameter inside it will impact the original data.
Note: Java does not support Call by Reference or Pass by Reference, as there is no concept of pointers in Java. But then how Java handles method calls for call by reference? We will discuss this next.
How Java Handles Method Calls: Call by Value in Java
Java only supports Pass by Value or Call by Value, which means all parameters to the method are copies whether they are primitives or objects that we shall now pass. This is where a common misconception arises when dealing with Java, but this is not true. Even when you pass an object to a method, Java does not pass the object to the method but rather passes a reference to that object. It means:
For primitive types, such as int, float, char, etc, a copy of the value is passed.
For objects, a copy of reference to the object is passed. A reference enables a user to perform operations on the fields and methods of the object but that exactly is a cloned one, a reference.
Call by Value in Primitive Data Types
For the case of primitive data types, like int, float, double, and others when these are replaced as parameters to a particular method; java simply takes its actual value and places it in the method’s parameter. Any changes made inside the method affect only the local copy, not the original value.
Example:
public class MainExample {
public static void main(String[] args) {
int num = 300;
modifyNum(num); // A copy of number is passed
System.out.println("Original number after method call: " + num);
}
public static void modifyNum(int num) {
num = 200; // Only local copy is changed
System.out.println("Answer number from method: " + num);
}
}
Output:
Answer number from method: 200
Original number after method call: 300
In this example, the num remains 300 after the method call because only the copy of the primitive value was changed.
When it comes to passing some objects as arguments, that is different from than primitive data type approach. Java passes the reference to the object by value, meaning that the method receives a copy of the reference to the object, not the actual object itself. When a reference to an object is passed to a method, the method doesn’t get the original object. Although it sounds as though call by reference applies here, it doesn’t because the reference is still being passed by value.
Example:
class Language {
String name;
}
public class MainClass {
public static void main(String[] args) {
Language lang = new Language();
lang.name = "Python";
modifyLanguage(lang);
System.out.println("Programming language name after method call: " + lang.name);
}
public static void modifyLanguage(Language lang) {
lang.name = "C++"; // Changing object field via reference
}
}
Output:
Programming language name after method call: C++
In this example, the field name of the Language object is changed to “C++” because the method works with the reference to the original object (even though the reference was passed by value). The original object won’t be impacted if we attempt to reassign the reference within the method.
Comparing Call by Value and Call by Reference
Below is a key difference between call by value and call by reference. Note that, call by reference doesn’t exist in Java, but still, it is good to know the difference between both:
Criteria
Call by Value
Call by Reference
Passed Parameter
A copy of the value is passed.
In this, a reference like memory address is passed in parameters.
Original argument
There is no changes to the actual argument outside the method.
The changes are reflected in the actual or original argument.
Supported by
It is supported by Java, C++, and other programming languages.
It is supported by C++, but not in Java.
Control over data
Less control (changes limited to method scope).
Full control (changes to the data reflect globally).
Misconception: Is Java Pass by Reference?
The idea that Java handles objects via “pass by reference” is a frequent one. But even with objects, Java is always passed by value. You are not passing the real object when you pass an object to a method; rather, you are passing the value of the reference to the object. For this reason, it is feasible to change object fields; however, the original object remains unaffected when the object reference is reassigned inside the method.
Example:
public class MainExample {
public static void main(String[] args) {
Integer n1 = new Integer(10);
Integer n2 = new Integer(20);
sum(n1, n2);
System.out.println("Sum from main method: " + (n1 + n2));
}
private static void sum(Integer n1, Integer n2) {
n1 = new Integer(30);
System.out.println("Sum from sum() method: " + (n1 + n2));
}
}
Output:
Sum from sum() method: 50
Sum from main method: 30
Two integer objects, n1 and n2, are provided to the sum() method in this example. It is important to realise that Java passes the value of the reference (also known as pass by value of reference) rather than the reference itself. This example shows that Java is not passed by reference since, even though n1 was reassigned inside sum(), the original n1 in main() stayed unaffected.
In Java, all method parameters are passed by value; it does not matter whether the parameters are primitives or objects. This is important because although object references are passed by value, they appear to be Call by reference. After all, the properties of an object can be modified in a method.
You will be in a better position to avoid ease of use at the expense of cleanliness, safety, and reliability of the code by mastering the nuances involved in call-by-value, especially as it regards objects in Java. Java indeed has no call-by-reference as C++ and other languages provide, however, it can still provide enough flexibility to appropriately deal with the complex scenarios of both primitives and objects.
FAQs
How do Call by Value work in non-primitive data types in Java?
Java sends a copy of the reference to the objects produced in the heap memory for non-primitive data types.
Does Java support Pass by Reference?
No, Java does not support Pass by reference. For all method arguments, Java uses pass-by-value. When passing objects, it passes the reference to the object, not the object itself. As a result, you can't change the reference to the original object in the calling method but can alter the object's properties via the reference.
Why do object values appear to change when passed to a method?
Java passes object references by value; however, it does so for the original object being referenced. Therefore, if the properties or state of the object are modified within the method, this will change outside the method. If, within that method, you assign the reference to a new object, then the original reference is untouched.
Can I simulate Pass by reference in Java?
No, Java is unable to simulate real Pass by Reference, as likely in languages such as C++. However, sending an object’s reference to a method allows you to change its properties, creating the appearance of a pass-by-reference.
What occurs when a method’s object reference is reassigned?
Within a method, reassigning an object reference only impacts the local copy of the reference. The invoking method’s original reference is still in place. This is a result of Java passing a copy of the reference rather than the original.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.