About Me

My photo
Northglenn, Colorado, United States
I'm primarily a BI Developer on the Microsoft stack. I do sometimes touch upon other Microsoft stacks ( web development, application development, and sql server development).

Tuesday, October 03, 2006

Java Question:

Well, I was just browsing the Code Project's website and found this interesting. Given the following Java code:

Posted by: Dominik Reichl

Integer i = 1;
Integer j = 1;
Integer n = 1000;
Integer m = 1000;

boolean b1 = (i == j);
boolean b2 = (n == m);

Now, what are b1 and b2?

Surprisingly b1 is true, b2 is false.


Posted by: Dominik Reichl

Ok, so here's the solution why it works this way
First of all, we are using Integer wrapper classes instead of the primitive int type. When compiling, the integral values 1 and 1000 are implicitely converted to Integer objects (called auto-boxing, from int to Integer).

So, we got 4 different Integer instances, right? No!

The Java VM automatically packs "small" primitive values into identical objects (1 is small, 1000 isn't small). You can easily verify this by pasting the code above into a small testing project and fire up the debugger: i and j reference the same object, while n and m reference different objects. The == operator is comparing references, therefore b1 is true (same references) and b2 is false (different references).

Currently "small" means any integer between -128 and 127. But according to Sun this can change to [-32768, +32767] in the future. This packing trick has been introduced to solve performance problems when doing arithmetic with wrapper classes.

No comments: