Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Short Constructor (Dan's Q) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Short Constructor (Dan Watch "Short Constructor (Dan New topic

Short Constructor (Dan's Q)

Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270

I dont understand why line 2 says parameter is an int? Notice, line 1 works just fine.
[ October 23, 2003: Message edited by: Cathy Song ]
Jessica Sant

Joined: Oct 17, 2001
Posts: 4313

that's because both operands are automagically promoted to an int, so the result is an int.
�5.6.2 Binary Numeric Promotion

If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted to float.
Otherwise, if either operand is of type long, the other is converted to long.
Otherwise, both operands are converted to type int.

so, you need to change your code to something like this:
Short obj2 = new Short( (short) (1-2) ); //line 2

- Jess
Blog:KnitClimbJava | Twitter: jsant | Ravelry: wingedsheep
Doug Dunn
Ranch Hand

Joined: Aug 03, 2003
Posts: 66
Yes, the previous responder is exactly right. You are casting the operands which must be fully evaluated before the binary operation can be performed. Thus your cast operators are meaningless. If you cast the result instead of the operands it will work.

Download a copy of <a href="" target="_blank" rel="nofollow"><i>"Mastering The Fundamentals of The Java Programming Language"</i></a>
Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
Thanks Jessica and Doug.
I agree. Here's the link:
subject: Short Constructor (Dan's Q)
Similar Threads
How many String Objects are created?
implicit and explicit conversion