Technical Tips, Tricks and Articles

Comparing Wrapper objects values in range –128 to 127

leave a comment »

While debugging through a bug that I encountered in one of my ongoing project. I came to know a strange behavior of Java. Consider the following code segment

1 Integer a = 10;
2 Integer b = 10;
3 
4 if (a == b){
5 	System.out.println("Two values are equal");
6 	}

If you look closely at line no 4, then you would realize that the code is actually comparing “Java objects”. Since “a” and “b” are not wrapper classes not primitive types.  But even then the condition is being true. Ok, some how this makes sense (at least till now unless you read this code segment)

1 Integer a = 150;
2 Integer b = 150;
3 
4 if (a == b){
5 	System.out.println("Two values are equal");
6 	}

Astonishingly, for the above code, the if statement would not execute true. Why?

Well, ever since Java has introduced “auto-boxing” feature, you’ll face this issue. Why is it so? Actually, compiler try to optimize things as much it can. For this, Java has a pool of values from –128 to 127. Whenever, there is some auto-boxing between these values, the reference object for the wrapper class will get the same memory location. In both cases, we are comparing “object references” but in first case, since the value was in the range for both objects hence, Java assigned the same reference location to both objects, making the condition “true” on comparing memory location for two objects.

Now, the question is why between –128 to 127?. Well, the smallest range of values for smallest wrapper class is between –128 to 127 i.e. Byte.

Written by ..alee

July 5, 2009 at 1:06 pm

Posted in code, interview, java, programming

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: