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:
final Integer a = 1;
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.
Integer b = a;
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.
b++;
This is a shorthand for the following statement:
b = new Integer(b.intValue() + 1);
And, coincidentally, the same for
b = b + 1;
The last statement:
b = 10
Is using autoboxing to shorthand this statement:
b = new Integer(10);
Hope this helps.
First of all, you must know that auto-boxing is happening here, you can read about that here.
Now only the b++
strikes me as non-straightforward. It is functionally equivalent to this code:
int bTemp = b.intValue();
bTemp++;
b = Integer.valueOf(bTemp);
Though the bytecode may be slightly different.
精彩评论