function won't change value of variable in java?

14,053

Solution 1

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

Solution 2

A boxed int is still immutable, and x in doChange refers to the parameter, not the field. To show what's going on, here is the explicitly boxed version of your code.

public static Integer x;

// parameter 'x' is hiding field 'x'
public static void doChange(Integer x)
{
    // Update parameter 'x', not field 'x', to point to
    // new Integer object with value 2.
    // Since 'x' is by-value, caller will not see change
    x = Integer.valueOf(2);
}

public static void main(String arg[]) {
    x = Integer.valueOf(1);
    doChange(x);
    System.out.println(x);
}
Share:
14,053
arshid dar
Author by

arshid dar

Updated on June 04, 2022

Comments

  • arshid dar
    arshid dar almost 2 years

    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);
    }
    
  • George Xavier
    George Xavier about 4 years
    Actually that is not autoboxing. Autoboxing would be directly assigning an into to an Integer object. For example: Integer x = 2; That would autobox 2 to the integer object. However Integer x = new Integer(2) is creating an object via the constructor of the Integer wrapper. No autoboxing occurs. In short, autoboxing involves assigning a primitive data type to an Object wrapper of that data type. Boolean boo = true; is autoboxing. Boolean boo = new Boolean(true) is not autoboxing. doChange(5) is autoboxing to doChange (new Integer(5)); automatically. int x = new Integer(5) is not autoboxing.