AM01
AM01

Reputation: 314

Java code snippet - playing with variable final - explanation required

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.

Upvotes: 2

Views: 192

Answers (2)

Mark Peters
Mark Peters

Reputation: 81134

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.

Upvotes: 2

Kylar
Kylar

Reputation: 9334

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.

Upvotes: 7

Related Questions