Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

S&B 1.5 Chapter 6, Question 4 explanation D

 
David Wooddall-Gainey
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I have several questions about self test questions. This is the first. D is one of the correct answers. Explanation: "it's ok to create a wrapper object with an expression, and unbox it for comparison with a primitive."

The code is:

Is s1 a primitive? I thought Short was a Short wrapper which could not be compared to an Integer.

Thanks
 
Lakuma Yalamanchili
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by David Wooddall-Gainey:



Is s1 a primitive? I thought Short was a Short wrapper which could not be compared to an Integer.


Line 1 : Two Short objects are created and the result 7 is casted to a short primitive using (short). Now since this is Java 5, it is auto boxed to a Short Object when you are assigning it to s1 --- I'm sure your confusion is not with this one!

Line 2 : s1 is an object being compared with an Integer object. In this case, both the objects are unboxed -> s1 to short and Integer to int and s1 is widened for comparision, so it becomes an int primitive being compared to an int primitive which is right!

The explanation which says:
"it's okay to create a wrapper object with an expression,
and unbox it for comparison with a primitive."

It means:
it's okay to create a wrapper object with an expression - refering to "new Integer(7+1)" part of the code
unbox it for comparison with a primitive - unboxing the Integer Object to compare with the already unboxed Short Object!

Hope this clarifies what you wanted to know..!!

But the catch thing you need to remember is that you cannot WIDEN and then BOX..!!
[ September 29, 2008: Message edited by: Lakuma Yalamanchili ]
 
David Wooddall-Gainey
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. I did not realize that both s1 and the INteger were being unboxed. Is this because you cannont compare a Short to an Integer?

Thanks again!
 
Lakuma Yalamanchili
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you cannot compare a Short and an Integer object and because unboxing and widening are allowed (but not WIDENing and BOXing) this is a valid action..!

Good luck to you!

Regards,
Lakuma!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic