• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Integer.equals() method

 
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider this-

Integer x = 343;
long L343 = 343L;
if (x.equals(L343)) <some code>;
if (x.equals(343)) <some code>;

How do the above if-conditions compile when the argument to the Integer.equals() method can only be an object of type Object?

Even the Javadoc is very precise-
Compares this object to the specified object. The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

What's more is that while the first one returns false, the second returns true!!

Regards
Percy
 
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
At Runtime there will be an Integer-Object. The Compiler will substitute "x.equals(343)" with something like "x.equals(new Integer(343))".
Keyword: AutoBoxing.

Or what was the problem exactly?
 
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
if (x.equals(L343)) System.out.println("first");
if (x.equals(343)) System.out.println("second");

My guess would be,

It autoboxes the primitive value before comparing.
In the first case, the primitive long gets autoboxed to Long object and in the second case the number 343 gets autoboxed to Integer object.

It returned true for the second one as both the objects are of same type.
 
Percy Dadabhoy
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ya...it makes sense....autoboxing and then the argument which is a reference of type Object holds a reference to either the Long object or the Integer object...and the Integer object returns true.

Thanks...
 
The City calls upon her steadfast protectors. Now for a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic