• 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

String doubts from K&b Self Test

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
from K&B- Pg 500 Q 4 ->
--- code ---
String s="-";
Integer x=343;
long L343=343L;
Short s1=7;
if(x.equals(L343)) s+=".e1";
if(s1 ==7) s+="=s";

------
First if return false
Second if retruns true
Can anyone explain why
Thanks in advcance
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Kanchan Narang:
from K&B- Pg 500 Q 4 ->
--- code ---
String s="-";
Integer x=343;
long L343=343L;
Short s1=7;
if(x.equals(L343)) s+=".e1";
if(s1 ==7) s+="=s";

------
First if return false
Second if retruns true
Can anyone explain why
Thanks in advcance



x refers to an instance of the wrapper class Integer. L343 is a primitive long, that is autoboxed to an instance of a Long when you send it as the parameter to equals. The way a wrapper class is defined, if you call the equals method and send an instance of an object that is not that wrapper class, you will get a false.

In the second if statement, when you compare a primitive to a wrapper, the wrapper will be autounboxed.
 
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Consider the following code and note that comparing a wrapper with a primitive will only return true if the primitive is of the corresponding type as the wrapper i.e Integer and int
reply
    Bookmark Topic Watch Topic
  • New Topic