• 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

Integer ref1,ref2;ref1=ref2=-128; ref1==ref2 give true but for the case -129 it give false

 
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Test
{
public static void main(String[] args)
{
System.out.println("\n\nSet 1");
Integer i = -128;
Integer j = -128;
System.out.println(i == j);
System.out.println(i.equals(j));

System.out.println("\n\nSet 2");
Integer i1 = -129;
Integer j1 = -129;
System.out.println(i1 == j1);
System.out.println(i1.equals(j1));

}
}

Output
Set 1
true
true


Set 2
false
true


Can anyone please explain me why "==" behaves differently as in the above code for Integer refs holding -128 & -129
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This has been discussed many, many times. Please use the search link at the top of the page to find the other discussions, like this one.

In fact, it gets asked so often that I've added it to the FAQ: http://faq.javaranch.com/java/JavaIntermediateFaq#integerAutoBoxing
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Chandan, welcome to javaranch.

Chandan please Use Code Tags to make you code more readable ...
 
reply
    Bookmark Topic Watch Topic
  • New Topic