Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt about wrapper Integer Class

 
Charandeep Singh
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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,
 
raj malhotra
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
May be all author are following JLS.May be sun people forget to include Long word there. can we ask sun about that
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic