Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why does this return false?

 
Ben Harrison
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Integer Ithree = new Integer(2); // 1
Integer Ifour = new Integer(2); // 2
System.out.println( Ithree == Ifour );

wouldn't they unbox and 2 == 2?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, because they are both references, == is reference comparison. If one of the operands were a primitive int, the other would be unboxed before the comparison.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You should also note that with autoboxing, equal values within the range of a byte will box to the same wrapper instance. Specifically, according to JLS - 5.1.7...
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.

For example...
 
Ben Harrison
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So based on:

"No, because they are both references, == is reference comparison. If one of the operands were a primitive int, the other would be unboxed before the comparison."

Wouldn't that mean that since they are both 2 they will point to the same reference variable making the == between them true?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, what Marc is talking about is autoboxing.

In your code, you are creating two different objects.

Whenever you use the new operator, a new object is created.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, I was kind of moving into another topic. Sorry for the confusion.
 
raja kanak
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hope the code above will help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic