• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Equality of Integers

 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can anyone explain this one for me:
public class SameObject {
public static void main(String args[]){
Integer i1=128;
Integer i2=128;
System.out.println(i1==i2);
}
}
The output will be false
Whereas
public class SameObject {
public static void main(String args[]){
Integer i1=18;
Integer i2=18;
System.out.println(i1==i2);
}
}
results in the output true
Why is this difference.
 
Ranch Hand
Posts: 88
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If assigned value for intergers is between -128 to 127 , then compiler checks for the pool (already contained values) . if it finds assigns from it . other wise it creates new one.

so if integer value is -128 to 127 , then it assignes same value for both objects . so it returns "true"
 
Ganesha Kumar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks.
But suppose if
Integer i1 =128;
int i2=128;
This would result in i1==i2 being true. This confuses me a bit
 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i checked, the first one gives "true" too
 
Gurpreet Bajaj
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i checked 4 i1=i2=129 and i1=i2=2007, both give true
 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


this ones print false, since integer constant pool range -128 - 127


But suppose if
Integer i1 =128;
int i2=128;
This would result in i1==i2 being true. This confuses me a bit



this ones print true, because there is autoboxing. i1 is unboxing to int, then comparing primitive result true
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic