| 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: 14672
|
|
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
|
 |
 |
|
|
subject: difference between != or ==
|
|
|