• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

'==' operatot behaving different for 1000 and 10.

 
Catherine austin
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got confused in the following code where it shows (i3==i4) but Not the same with (i2==i4).
Why this code behaves differently. Here's the code

Output :Same Object-I



Kindly clear this doubt. I shall be very thankfull to u.
 
Muneeswaran Balasubramanian
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Austin,

If you create the integer like



It creates the integer object by auto boxing.When you create the Integer from -128 to 127 by using the above syntax, it creates the object in the constant pool like create the string in string literal pool.
If you create the Integer with the value more than 127,it creates the object in the heap.So at the time of check equality using == it returns false.

The above rule is applicable for Byte and Short also.But not applicable for Float and Double.

 
Darryl Burke
Bartender
Posts: 5148
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, that's not correct. There's no 'constant pool' for Integers. Autoboxing uses values cached by the Integer class.

The behavior is as mandated by the JLS.
http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#190730
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.
 
Catherine austin
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Muneeswaran and Darryl But Darryl can you explain me the real cause of this absurd behaviour . Since my exam is next weak i need to know all possible answers .
 
Scotty Mitchell
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Catherine austin wrote:Thanks Muneeswaran and Darryl But Darryl can you explain me the real cause of this absurd behaviour . Since my exam is next weak i need to know all possible answers .


His post has the real cause of the absurd behavior. JLS mandates that if you have a boxing of an int or short between -128 to 127 then when evaluating == it is true.
 
Javin Paul
Ranch Hand
Posts: 295
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

yes that's correct, JVM returns same object for integer range -128 to 127. you may find my blogpost What is the problem while using "==" in autoboxing world in Java 5 interesting.
 
Catherine austin
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Javin
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic