Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable and pass by value

I have the following code which has
a mutable Person class, String and a method to modify the instances of String and Person

    class Person{

int a = 8;

public int getA() {
    return a;
}

public void setA(int a) {
    this.a = a;
}

@Override
public String toString() {
    return "Person [a=" + a + "]";
}

  }

--

public class TestMutable {
public static void main(String[] args)
{
    Person p = new Person();
    p.setA(34);


    String s = "bar";

             modifyObject(s, p);   //Call to modify objects

    System.out.println(s);
    System.out.println(p);

}



private static void modifyObject(String str, Person p)
{

        str = "foo";
        p.setA(45);

}

  }

The output is as expected. It prints

           bar
          Person [a=45]

Now, my question is

What is happening at the place you say str="foo" ?

Initially let's assume that s='bar' and the data resides in 0x100 memory

Now the reference of string is passed to another method, the other method tries to change the contents of the memory location(0x100) to 'foo' using s="foo". Is this what is happening, or is 'foo' is created in differennt memory location ?

Does java pass references by value ?

like image 560
Vinoth Kumar C M Avatar asked Nov 24 '11 12:11

Vinoth Kumar C M


People also ask

What is an immutable value?

An immutable value is one whose content cannot be changed without creating an entirely new value. In JavaScript, primitive values are immutable — once a primitive value is created, it cannot be changed, although the variable that holds it may be reassigned another value.

Are mutable objects passed by reference?

If you pass a mutable object, like a list or a dictionary, it's like pass-by-reference. Again, you can't reassign the parameter to something else, but you can modify the object that you get.

Can you inherit from an immutable class?

On the other hand, Inheritance describes a relationship between classes (i.e. the structure of a program's source code) and has absolutely nothing whatsoever to do with the state of objects or variables, so as far as immutability is concerned, inheritance is a totally irrelevant and unconnected concept.

What is the difference between pass by value and pass-by-reference in Java?

Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that's why it's called pass by value. Pass by Reference: An alias or reference to the actual parameter is passed to the method, that's why it's called pass by reference.


2 Answers

Java always passes arguments by value NOT by reference.


Let me explain this through an example:

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 change 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");
     }
}

I will explain this in steps:

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");

enter image description here

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)

enter image description here

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

changeReference(f);

enter image description here

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");

enter image description here

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

enter image description here


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

enter image description here

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

enter image description here

I hope you understand now how passing objects as arguments works in Java :)

like image 100
Eng.Fouad Avatar answered Oct 01 '22 01:10

Eng.Fouad


In modifyObject, When you assign to str, you're not mutating str, you're setting it so that it points to a different object. Since it's passed by value, the str pointer local to your modifyObject method is a copy of the s pointer in main, so when you change the former, it does not affect le later.

On the other hand, when it comes to p, the one in modifyObject is still a copy of the one in main, but both pointers refer to the very same object in memory, hence if you call a method on it from modifyObject, you're actually mutating the thing pointed to by p.

like image 43
Romain Avatar answered Oct 01 '22 00:10

Romain