• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

difference between != or ==

 
mukki pandey
Ranch Hand
Posts: 58
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
ramesh maredu
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
mukki pandey
Ranch Hand
Posts: 58
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i want to know when != encounters what are the vlaues compared exactly does it take memory reference or somehting else
 
ramesh maredu
Ranch Hand
Posts: 210
Eclipse IDE Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
!= or == when you used it on object references it checks whether they point to same object or not
 
mukki pandey
Ranch Hand
Posts: 58
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic