This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt about wrapper Integer Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt about wrapper Integer Class" Watch "Doubt about wrapper Integer Class" New topic
Author

Doubt about wrapper Integer Class

Charandeep Singh
Ranch Hand

Joined: May 06, 2007
Posts: 57
import java.lang.*;

class EqualityChk
{
public static void main(String[] args)
{
Integer k=127;// line 1
Integer g=127;//line 2
if(k==g)
System.out.println(" K AND G ARE EQUAL ");
else
System.out.println(" NOT EQUAL ");
}
}

Hi all
The output of the above program is
K AND G ARE EQUAL

But if I modify line 1 and line 2 and change there values to 128
the output changes to NOT EQUAL can any body tell me what is the exact reason for this inconsistency?

Thanks
Charandeep
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Hi,

Straight from book K&B:


Using == with wrappers is tricky; wrappers with the same small values
(typically lower than 127), will be ==, larger values will not be ==.


This applies to Byte,Short,Character,Integer only. The JLS does not mention the behavior of Long in this case which gives the same result though. That't Long can't be treated as all other four;


Thanks,


cmbhatt
raj malhotra
Ranch Hand

Joined: Feb 22, 2007
Posts: 285
But If a question comes for Long what to do:

Long k=128l;
Long g=128l;

As JLS doesnot mention for a Long,can we select the same reason in the exam?
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
Originally posted by raj malhotra:
But If a question comes for Long what to do:

Long k=128l;
Long g=128l;

As JLS doesnot mention for a Long,can we select the same reason in the exam?


I think we should stick to the rules. I don't see any book talking about the guaranteed behavior of Long in this case.

Thanks,
raj malhotra
Ranch Hand

Joined: Feb 22, 2007
Posts: 285
May be all author are following JLS.May be sun people forget to include Long word there. can we ask sun about that
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt about wrapper Integer Class