Java: Pass by Reference or Pass by Value? – Explained

The most asked question in the interview and confuse everyone all the time.7 min


is-java-pass-by-value-or-pass-by-reference-interview-questions

Java is always pass-by-value, NOT by reference. (Remember – Java pass by value)

Unfortunately, we never handle an object at all, instead of juggling object handles called references (which are passed by value of course).

The chosen terminology and semantics easily confuse many beginners.

This will give you some insights into how Java really works to the point that in your next discussion about Java passing by reference or passing by value you’ll just smile 😊

Step one please erase from your mind that word that starts with ‘p’ “_ _ _ _ _ _ _”, especially if you come from other programming languages. Java and ‘p’ cannot be written in the same book, forum, or even text.

Step two remember that when you pass Object into a method, you’re passing the Object reference and not the Object itself.

  • Student: Master, does this mean that Java is pass-by-reference?
  • Master: Grasshopper, No.

Now think of what an Object’s reference/variable does/is:

  1. A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).
  2. When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bPd086a. — 3bPd086a represents a way to get to the passed object.
  3. So you’re just passing 3bPd086a, which is the value of the reference.
  4. You’re passing the value of the reference and not the reference itself (and not the object).
  5. This value is actually COPIED and given to the method.

Now, Compile/execute the below program in your mind or on your console.

Person person;
person = new Person("Tom");
changeName(person);
//I didn't use Person person below as an argument to be nice
static void changeName(Person anotherReferenceToTheSamePersonObject) {
  anotherReferenceToTheSamePersonObject.setName("Jerry");
}
What just happened here?
  • The variable person is created in line #1 and it’s null at the beginning.
  • A new Person Object is created in line #2, stored in memory, and the variable person is given the reference to the Person object. That is its address. Let’s say 3bPd086a.
  • The variable person holding the address of the Object is passed to the function in line #3.
  • On line #4 you can listen to the sound of silence
  • Check the comment on line #5
  • A method local variable –anotherReferenceToTheSamePersonObject– is created and then comes the magic in line #6:
  • The variable/reference person is copied bit-by-bit and passed to anotherReferenceToTheSamePersonObject inside the function.
  • No new instances of Person are created.
  • Both “person” and “anotherReferenceToTheSamePersonObject” hold the same value of 3bPd086a.
  • Don’t try this but person==anotherReferenceToTheSamePersonObject would be true.
  • Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap, and NOT A COPY.

One picture is worth a thousand words.

Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!

If you didn’t get it then just trust me and remember that it’s better to say that Java is pass by value. Well, pass by reference value. Oh well, even better is pass-by-copy-of-the-variable-value! 😉

Now feel free to hate me but note that given this there is no difference between passing primitive data types and Objects when talking about method arguments.

You always pass a copy of the bits of the value of the reference!

  • If it’s a primitive data type these bits will contain the value of the primitive data type itself.
  • If it’s an Object the bits will contain the value of the address that tells the JVM how to get to the Object.

Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you’ll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!

And

The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.

Let me give you two examples for better understanding.

Example 1: Take a look at this example.
public static void main(String[] args) {
    Dog aDog = new Dog("Max");
    Dog oldDog = aDog;

    // we pass the object to foo
    foo(aDog);
    // aDog variable is still pointing to the "Max" dog when foo(...) returns
    aDog.getName().equals("Max"); // true
    aDog.getName().equals("Fifi"); // false
    aDog == oldDog; // true
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true
    // change d inside of foo() to point to a new Dog instance "Fifi"
    d = new Dog("Fifi");
    d.getName().equals("Fifi"); // true
}

In the example above aDog.getName() will still return "Max". The value aDog within main is not changed in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.

Likewise:

public static void main(String[] args) {
    Dog aDog = new Dog("Max");
    Dog oldDog = aDog;

    foo(aDog);
    // when foo(...) returns, the name of the dog has been changed to "Fifi"
    aDog.getName().equals("Fifi"); // true
    // but it is still the same dog:
    aDog == oldDog; // true
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true
    // this changes the name of d to be "Fifi"
    d.setName("Fifi");
}

In the above example, Fifi is the dog's name after a call to foo(aDog) because the object's name was set inside of foo(...). Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog, but it is not possible to change the value of the variable aDog itself.

Example 2: Take a look at it,
public class Main {

     public static void main(String[] args) {
          Foo f = new Foo("f");
          changeReference(f); // It won't change the reference!
          modifyReference(f); // It will modify the object that the reference variable "f" refers to!
     }

     public static void changeReference(Foo a) {
          Foo b = new Foo("b");
          a = b;
     }

     public static void modifyReference(Foo c) {
          c.setAttribute("c");
     }

}
So what are we doing here?
  1. Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f".
Foo f = new Foo("f");


2. From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null.

public static void changeReference(Foo a)

3. As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.

changeReference(f);


4. Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".

Foo b = new Foo("b");

5. a = b is re-assigning the reference a NOT f to the object whose attribute is "b".

6. As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".

7. c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's the same object that reference f points to it.

This is how passing objects as arguments work in Java.

Important Key point to keep in mind:

Sometimes people get confused when passing by reference. It’s possible to change the object that the reference refers to (giving the impression of pass-by-reference), but it is not possible to modify the reference itself. So it still remains pass-by-value.

Hope your doubts are clear regarding pass by value or pass by reference.


I obtain an immense amount of satisfaction from helping others attain their goals and reach their potential through technology. Even if you wish to reach out and say "Hello", I sincerely appreciate all of the wonderful correspondence I receive each day from readers. You all enrich my life, and I hope I am able to do the same for you all as well.

If you find joy and value in what I do, please consider supporting my work with a donation — however much you can afford, it means and helps more than you can imagine.

You can give tips too using Buy me a coffee.

adsense


Discover more from 9Mood

Subscribe to get the latest posts sent to your email.


Like it? Share with your friends!

What's Your Reaction?

Lol Lol
0
Lol
WTF WTF
0
WTF
Cute Cute
1
Cute
Love Love
1
Love
Vomit Vomit
0
Vomit
Cry Cry
0
Cry
Wow Wow
1
Wow
Fail Fail
0
Fail
Angry Angry
0
Angry
Rakshit Shah

Legend

Hey Moodies, Kem chho ? - Majama? (Yeah, You guessed Right! I am from Gujarat, India) 25, Computer Engineer, Foodie, Gamer, Coder and may be a Traveller . > If I can’t, who else will? < You can reach out me by “Rakshitshah94” on 9MOodQuoraMediumGithubInstagramsnapchattwitter, Even you can also google it to see me. I am everywhere, But I am not God. Feel free to text me.

0 Comments

Leave a Reply

Choose A Format
Story
Formatted Text with Embeds and Visuals
List
The Classic Internet Listicles
Ranked List
Upvote or downvote to decide the best list item
Open List
Submit your own item and vote up for the best submission
Countdown
The Classic Internet Countdowns
Meme
Upload your own images to make custom memes
Poll
Voting to make decisions or determine opinions
Trivia quiz
Series of questions with right and wrong answers that intends to check knowledge
Personality quiz
Series of questions that intends to reveal something about the personality
is avocado good for breakfast? Sustainability Tips for Living Green Daily Photos Taken At Right Moment