I have written this code and I wanted to know why the value of the object being referenced is not being changed
All calls in java are call by value. But when the call refers to the same object , why is the object not being updated
class Main {
public static void main(String[] args) {
Integer n = 3;
triple(n);
System.out.println("Hello world! " + n);
}
public static void triple(Integer x)
{
x *= 8;
System.out.println("Hello world! " + x);
}
}
Actual output
Hello world! 24
Hello world! 3
But I thought that output should be
Hello world! 24
Hello world! 24
Is it so because of the unboxing and autoboxing for the Integer class that a new object is created with the same name as 'x', because Integer is immutable that is locally available and which does not point to the argument/ the object being passed - n.
When you pass the Integer n
to the triple
method you are actually passing the value of the reference of the Integer
object n
.
So in the triple
method another local variable x
is pointing to the this reference value when it gets called. Inside the method when it multiplies the value of this Integer object with 8
it will create another new instance of the Integer
as Integer
is immutable to which the local variable x
will point to.
So you won't see this new value in the print statement System.out.println("Hello world! " + n);
as n
is still pointing to the old instance of the Integer which is still 3
.
If you try this with a StringBuilder
you would get the result you are expecting:
public static void main(String[] args) {
StringBuilder n = new StringBuilder("foo");
triple(n);
System.out.println("Hello world! " + n);
}
public static void triple(StringBuilder s) {
s.append("bar");
System.out.println("Hello world! " + s);
}
Here the output will be:
Hello world! foobar
Hello world! foobar
This is because StringBuilder
is mutable, if triple
is modifying the data by appending to it, both the original pointer n
and the new pointer s
will point to the same value of the object reference.