Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object value doesn't change

Tags:

java

class smth{
    public static void main(String[] args){
        private Integer x = new Integer(17);
        inc(x);
        System.out.print("x="+x);
    }
    public static void inc(Integer x){
        x++;
        System.out.println("n="+x);
    }
}

output: n=18; x=17;

Integer is an object and I don't understand why the value of x did not change in this case.

like image 668
Sandro Dolidze Avatar asked Mar 20 '26 21:03

Sandro Dolidze


1 Answers

Cause Integer is immutable object. When you send it to method, new reference to it is created. When you do increment, reference inside method is reassigned to new Integer with value 18 but reference inside main is still referencing to old Integer with value 17.

like image 132
bellum Avatar answered Mar 22 '26 09:03

bellum



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!