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.
Cause
Integeris immutable object. When you send it to method, new reference to it is created. When you do increment, reference inside method is reassigned to newIntegerwith value18but reference insidemainis still referencing to oldIntegerwith value17.