aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes difference between != or == Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "difference between != or ==" Watch "difference between != or ==" New topic
Author

difference between != or ==

mukki pandey
Ranch Hand

Joined: Sep 22, 2008
Posts: 58
Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");

Produces the output:
different objects
meaningfully equal

Integer i3 = 10;
Integer i4 = 10;
if(i3 == i4) System.out.println("same object");
if(i3.equals(i4)) System.out.println("meaningfully equal");
This example produces the output:
same object
meaningfully equal

why != and == both pass the if condition ;i know that == looks if both variables have same value but why does != ??
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

Java Language Specification 5.1.7 Boxing Conversion
If p is a value of type int, then boxing conversion converts p into a reference ref of class and type Integer, such that ref.intValue() == p

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

Try the same example with 127 and 128
[ September 30, 2008: Message edited by: Christophe Verre ]

[My Blog]
All roads lead to JavaRanch
ramesh maredu
Ranch Hand

Joined: Mar 15, 2008
Posts: 210

Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1.equals(i2)) System.out.println("meaningfully equal");

modify i1 and i2 values to 127 your output will change, because Integer class maintains cache for values in the range of -128 to 127. So when ever you use literal assignment it takes values from cache.


SCJP 1.5 94%.
The greatest glory in living lies not in never falling, but in rising every time we fall.
mukki pandey
Ranch Hand

Joined: Sep 22, 2008
Posts: 58
i want to know when != encounters what are the vlaues compared exactly does it take memory reference or somehting else
ramesh maredu
Ranch Hand

Joined: Mar 15, 2008
Posts: 210

!= or == when you used it on object references it checks whether they point to same object or not
mukki pandey
Ranch Hand

Joined: Sep 22, 2008
Posts: 58
Integer i1 = 1000;
Integer i2 = 1000;
if(i1 != i2) System.out.println("different objects");
if(i1 == i2) System.out.println("same object");

what will be the output
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: difference between != or ==