Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • 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
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

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
 
Destroy anything that stands in your way. Except this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic