This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why does this return false? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why does this return false?" Watch "why does this return false?" New topic
Author

why does this return false?

Ben Harrison
Greenhorn

Joined: Jan 26, 2006
Posts: 27
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

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Aug 31, 2004
Posts: 11343

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...


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Ben Harrison
Greenhorn

Joined: Jan 26, 2006
Posts: 27
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

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Aug 31, 2004
Posts: 11343

Yeah, I was kind of moving into another topic. Sorry for the confusion.
raja kanak
Ranch Hand

Joined: Oct 18, 2006
Posts: 135

Hope the code above will help.


live
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: why does this return false?
 
Similar Threads
Why it is false?
Integer == Integer?
Please explain the answers...
Garbase Collection and Java Litral Pool
Equality Problem