I know that everything in java is passed by value but shouldn't the below code print 2 instead of 1.
All I am doing is passing Integer and changing its value. Why is it printing 1 instead of 2 ?
public static Integer x;
public static void doChange(Integer x) {
x = 2;
}
public static void main(String arg[]) {
x = 1;
doChange(x);
System.out.println(x);
}
thank you so much for your answers. i think i know now what is happening under the hood. i think the reason i am not able to see changes in main function is because integer is immutable and when i am assigning new value to it, its creating new object and assigning to the reference x;
if we can repeat same example with mutable data we ll see different output.
public static StringBuilder x;
public static void doChange(StringBuilder x)
{
x.append("world");
}
public static void main(String arg[]) {
x = new StringBuilder("hello ");
doChange(x);
System.out.println(x);
}
output: hello world
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With