| Author |
how is this possible please explain
|
Shashank Agarwalg
Ranch Hand
Joined: Mar 03, 2010
Posts: 110
|
|
Integer i1=1000;
Integer i2=1000;
if(i1!=i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");
output
different objects //how is this possible please explain
meaningfully equal
b]Integer i3=10;
Integer i4=10;
if(i3==i4) System.out.println("same objects");
if(i3.equals(i4)) System.out.println("meaningfully equal");
output
same objects //how is this possible please explain
meaningfully equal
how if(i3==i4) and if(i1!=i2) both can be true
|
Trying to win the world.....................
SCJP 6.0 , SCWCD/OCPJWCD 5, BlackBerry Developer
|
 |
marc weber
Sheriff
Joined: Aug 31, 2004
Posts: 11343
|
|
This is due to autoboxing. In your first example, the value being boxed is outside the range -128 to 127. In your second example, the value is within that range. As explained under JLS - 5.1.7 Boxing Conversion...
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.
|
"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
|
 |
Shashank Agarwalg
Ranch Hand
Joined: Mar 03, 2010
Posts: 110
|
|
|
Thanks for the solution.
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
Please note that this exact same question has been asked and answered here many times before:
http://www.coderanch.com/t/491902/java/java/equals-Please-help
http://www.coderanch.com/t/470467/java/java/wrapper-class-code
http://www.coderanch.com/t/496079/java/java/Query-boxing-why-both-works
http://www.coderanch.com/t/435562/java/java/query-Wrapper-classes
http://www.coderanch.com/t/410771/java/java/wrappers
Please do a search before you post, you'll also find answers quicker if you do that.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
 |
|
|
subject: how is this possible please explain
|
|
|