final Integer a = 1;
Integer b = a;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 1
b++;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 2
b = b + 1;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 3
b = 10;
System.out.println("a: " + a); // prints 1
System.out.println("b: " + b); // prints 10
It would be great if somebody could explain the code output, expecially with relation to variable B.
Ok, let’s start with this:
You’ve created a final reference to an Integer object, which was autoboxed from a primitive int.
This reference can be assigned exactly once, and never again.
here you’ve created a second reference to the same object, but this reference is not final, so you can reassign it at your leisure.
This is a shorthand for the following statement:
And, coincidentally, the same for
The last statement:
Is using autoboxing to shorthand this statement:
Hope this helps.