Home Java Call By Value & Call By Reference in Java

Call By Value & Call By Reference in Java

by Mahesh More
10722 views
Call By Value & Call By Reference in Java

Hey, Tea Lovers! Today we will take a look at the basic but tricky interview question, Call By Value & Call By Reference in Java. Both beginners and experienced developers get this question in interviews. It’s a technical interviewer’s favorite question. This post is one of the many in the series of Interview Questions, where we don’t just hang you with one line answer, rather try to explain it so that it gets fit into your head.


You can follow me on social media via @coderstea on TwitterLinkedinFacebook, or Instagram. We also share high-quality videos about programming on our Youtube channel. You can also publish your post on CodersTea, just share your thought on Contact Us or let us know in the comments.

I know you are in a hurry for the interview. So without any further ado let’s prepare your cup of tea to sip and code.

Why Call By Value & Call By Reference ???

A method or a function can be called in two ways. One is Call by Value and the other is Call by Reference, both ways are generally differentiated by the type of the value passed to them as an input or as a parameter.

Before we start, let me clear one thing, in Java, there is only call by value and not call by reference.

Call By Value

Call by Value is an approach where the passing of a parameter to a function is carried out by copying the actual value of a given variable ( or constant or anything that holds data)

This means when we call a method with passing argument value of the parameter, then this argument value is copied into a portion of memory (depending on the type), and a copy of the value is passed to the parameter of the calling method.

⚠️ In Java there is only call by value, not call by reference.

Call By Reference

Call by Reference is an approach that passes a reference (i.e. address) of the value to a method.

This means when we call the method by passing the copy of a reference (i.e. address) to the value of that method & not a copy of value itself, then the calling method has a reference (i.e. address) of that value.

When the calling method changes the reference of the value the original reference also changes.

Confused? See the table below.

Difference Between Call By Value & Call By Reference

Call By ValueCall By Reference
The original value is not modified.The original value is modified.
A copy of the variable is passedVariable itself is passed or Reference of that Variable is passed.
The actual and formal arguments will be created on the different memory locations.The actual and formal arguments will be created in the same memory location.
Copy of the Variables are directly passed to the methodThe pointer of that variables is required to store the address of that variables.
Call By Value vs Reference

Why In Java there is only Call by Value, not Call by Reference ???

By definition, the call by reference is where we are passing the reference (i.e. address) of that variable. To do that, we need to store the address first which will require a pointer (in C, its passed as *variableName). And as we know in java we do not have a pointer so it is not possible to pass a reference (i.e address) and perform call-by-reference.

Java does not support Pointers that’s why Java does not support Call by Reference. But C/C++ supports pointers, hence these languages support Call by Reference.

And Why Java does not support Pointer you may ask? Well, that is another debatable topic, that we can discuss in some other article, till that checkout this stackoverflow page, which gives you some glimpse of it.

But still, we can achieve Call By Reference in Java with the help of Object Dramatic Behavior.

Call By Reference in Java, But How ???

Java always uses call by value. which means the method gets a copy of all parameter values, and the method can’t modify the content of that variable passed. Java uses two kinds of method parameters:

  1. Java Primitive Types
  2. Java Object References

It seems very straightforward and simple, as when you pass primitive types to a method. But it is dramatic when it comes to passing the objects to the method. when an object is passed to a method, the method gets a copy of the object reference, and both the original and the formal copy refer to the same object, therefore within the calling method, the state of an object parameter can be changed.

So let’s understand the above two method parameters in detail with an example.

Passing Java Primitive Data Types as Parameter to a Method

In the case of the primitive data type parameter, the original value is not changed. Let’s take a simple example:

Code

public class PrimitiveDataInAction {
  public static void main(String[] args) {

    int someValue = 50;

    System.out.println("Before method call :: " + someValue);
    
    modified(someValue);
    
    System.out.println("After method call :: " + someValue);
  }

  public static void modified(int someValue) {
    System.out.println("exiting name :: " + someValue);
    // modifying the parameter
    someValue = 15;

    System.out.println("modified name :: " + someValue);
  }
}

Output

Before method call :: 50
exiting name :: 50
modified name :: 15
After method call :: 50

Process finished with exit code 0

When you pass primitive data type variable to a method, it creates a local copy for that method, & perform whatever operation mentioned in method & once this variable comes out of this method so that method local copy get delete from memory

& previous value which before calling that variable it gets loaded.

Java Object References

In the case of call-by-value with Java Object Reference type, the original value is changed. Let’s take a simple example:

Code

class JavaObjectReferencesInAction {
  public static void main(String[] args) {

    List <String> listOfString = new ArrayList < > ();
    listOfString.add("Mahesh");

    System.out.println("Before modified :: " + listOfString);

    modified(listOfString);

    System.out.println("After modified :: " + listOfString);
  }

  public static void modified(List < String > listOfString) {
    // modifying the string
    listOfString.add("Imran");
  }
} 

Output

Before modified :: [Mahesh]
exiting listOfString :: [Mahesh]
modified listOfString :: [Mahesh, Imran]
After modified :: [Mahesh, Imran]

Process finished with exit code 0

Let’s see how it works.

  • In above example we have created an object of ArrayList and added one string value Mahesh in it. Now the List have a data as one String with value Mahesh.
  • In Next Line we called the method modified which takes a List and adds one more String Imran to the same given List
  • But when we call that modified method the Java Object Reference takes place instead of value. It passes the reference of list which is nothing but the actual object of list
  • This results into modifying the original list also.

Conclusion

We talked about one of the tricky interview questions as Call By Value & Call By Reference in Java in detail. For beginners, it might be a lot to digest but trust me, it will get cleared in your head once you start playing with it.

Most of the time interview is about tricky questions and answers like this. Just don’t lose hope. Gain your knowledge not by reading only but by working on some stuff side by side.

I have posted some posts that will help you, such as “Mistakes Probably Every Programmer and I Made in the Beginning”, “Most Loved Interview Question: How HashMap works in Java” & “interview series

Hope you liked the post. If you want to discuss something and clear out some questions related or unrelated to this topic, please free to comment. or Follow us on social media.

See you in the next post. HAKUNA MATATA!!!

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Dude
Dude
February 19, 2022 11:05 pm

Java is call by reference, its just not allowing pointer operations. Where there is null there is call by reference.

Coder
Coder
February 20, 2022 1:33 pm

We can’t say pass by value a times..Summary is simple…Primitive types are passes by values always..Objects (on heap) are passed by reference always..

Intrestingly Reference params are passed value, which means any changes to object via passed reference will reflect original object, but of reference points to diff object, reference in calling function still points to original object.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More