• 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
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

doubt about boxing conversions

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Boxing4 {
public static void main(String[] args) {
Integer i = 10;
Integer j = 10;

System.out.print(i==j);
System.out.print(i.equals(j));

}
}

Output is truetrue

But if i modify this code as

public class Boxing4 {
public static void main(String[] args) {
Integer k = 1000;
Integer l = 1000;

System.out.println(k==l);
System.out.print(k.equals(l));
}
}

Now the output is falsetrue

Can somebody explain the difference?
Thanks in advance !
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
See our SCJP FAQ: Why do separate autoboxing conversions sometimes return the same reference?
 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
I had the same doubt
the edge case is 127 and 128
on 127 you will get equal as true while 128 will be false

Reason coming Straight from book K&B:

Using == with wrappers is tricky; wrappers with the same small values
(typically lower than 127), will be ==, larger values will not be ==.



This applies to Byte,Short,Character,Integer only. The JLS does not mention the behavior of Long in this case which gives the same result though. That't Long can't be treated as all other four;
 
please buy my thing and then I'll have more money:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic