Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapper classes and call by reference in java [duplicate]

Tags:

java

Below is my code:

class Demo{
public static void main(String[] args) {
    Integer i = new Integer(12);

    System.out.println(i);

    modify(i);

    System.out.println(i);

}
private static void modify(Integer i) {

    i= i + 1;
    System.out.println(i);
}

}

The OUTPUT of the above CODE is 12 12 but as I know, we are passing the wrapper object "i", it means it should be "Call by reference",Then the value should change to 13.but its 12. Any one has proper explanation for this?

like image 697
ShyamD Avatar asked Dec 02 '22 20:12

ShyamD


1 Answers

References are passed by value, and besides of that Integer is immutable.

When passing i to the method modify the value of the reference is passed (the reference is local to that method) and when you assign another object to it you only modify that local reference/variable holding the reference. The original remains unchanged.

Immutable means that an object once created / instantiated it not possible to change its state any more.

like image 180
A4L Avatar answered Dec 20 '22 20:12

A4L