Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function won't change value of variable in java?

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);
}
like image 349
arshid dar Avatar asked Feb 20 '26 07:02

arshid dar


1 Answers

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

like image 118
arshid dar Avatar answered Feb 22 '26 19:02

arshid dar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!