Here's a quick "gotcha" about which you might not have known. Consider the following code:
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.
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:
I thought that was kind of interesting.
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
- 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
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".
Page 1 of 1
← January 2022 →
| S | M | T | W | T | F | S |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 | 31 |
My Blog Links
Recent Entries
-
-
-
Play Framework 2.1: The Bloom Is Off The Roseon Apr 30 2013 03:50 AM
-
-
Useful Java Utilities and Frameworkson Jul 25 2008 08:56 AM
Recent Comments
Search My Blog
6 user(s) viewing
6 Guests
0 member(s)
0 anonymous member(s)
0 member(s)
0 anonymous member(s)



2 Comments









|