Subscribe to Stupid Java Tricks        RSS Feed
-----

Quick post about "==" operator

Icon 2 Comments
Here's a quick "gotcha" about which you might not have known. Consider the following code:

Integer i1 = 200;
Integer i2 = 200;
String s = (i1 == i2) ? "equal" : "not equal";
System.out.println(s);


What is the output? That's an easy one, right? The output is not equal because, although these Ineger objects contain the same int value, they refer to different objects. Consider the following modification to the code, however.

Integer i1 = 75; // <--- changed
Integer i2 = 75; // <--- changed
String s = (i1 == i2) ? "equal" : "not equal";
System.out.println(s);


So, what's the output now? You can probably guess from the tone that it's probably not what you'd expect. Give up? The output is equal! So what the heck is going on here? Well, it turns out that, in order to save memory, two instances of the following wrapper objects will be == if their values are equal:

Quote

- Boolean
- Byte
- Character from \u0000 to \u007f (7f is 127 in decimal)
- Short and Integer from -128 to 127


I thought that was kind of interesting.

2 Comments On This Entry

Page 1 of 1

Videege Icon

23 December 2007 - 01:07 AM
Yet another giant violation of the zero-one-infinity rule and one of the many reasons why Java is a terrible, terrible "beginner language".
0

RodgerB Icon

24 December 2007 - 05:40 AM
Wow interesting find! Thats insane :crazy: .
0
Page 1 of 1

Recent Entries

December 2014

S M T W T F S
 123456
78910111213
14151617181920
21 22 2324252627
28293031   

My Picture

Recent Comments

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)