views:

66

answers:

2
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.

+7  A: 

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.

Kylar
I believe autoboxing uses `Integer.valueOf`, not `new Integer`.
Jonathon
You're probably right - I was more interested in the concepts than the specifics. In that it creates a new one (or returns from the internal cache) for the assignment.
Kylar
Probably doesn't matter for this example, but I believe it uses `Integer.valueOf(...)` and not `new Integer(...)` so `==` still works.
j flemm
But why if b++ is b = new Integer(b.intValue() +1) then print out print 1 ? This is standard post incremenation so the b have the value 2 in case after that sysout
Vash
Thank you very much. Eclipse scrappage wasn't outputing the correct value for b++, hence the confusion.Much appreciate your input, its really informative.
AM01
@j flemm: Never, ever, ever count on that in real code. Just way too easy to make mistakes, even if the JLS specifies a minimum integer cache size. `==` only works if the value the Integer represents is within the pool of cached integers.
Mark Peters
@Mark Peter: At the begining in the code sample the result was 1, after some time, it was changed to 2.
Vash
@Mark Peters: I never would. `.equals(...)` is there for a reason. But `new Integer(...)` is usually regarded as bad form since it's never better and possibly worse. I just used `==` to check it in my IDE since I wasn't in the mood to check the bytecode.
j flemm
Oh absolutely, `new Integer(int)` is always wrong. If they could design it from scratch they'd probably make the constructor private.
Mark Peters
+1  A: 

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.

Mark Peters