It's not a secret anymore!
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Narrowing conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Narrowing conversion" Watch "Narrowing conversion" New topic

Narrowing conversion

Rashmi Tambe
Ranch Hand

Joined: Aug 07, 2001
Posts: 418
Khalid mughal (page 48) says

Narrowing conversion betn. char, byte, short values on assignment always requires an explicit cast , even if value is in range of destination data type.

byte b = 20; // narrowing conversion int -> byte
this compiles correctly even if explicit cast is not stated.
here 20 is in range of byte. then according to KM,Why explicite cast not required???
thanx in advance...
[This message has been edited by Rashmi Gunjotikar (edited November 28, 2001).]
kinnu jemmy

Joined: Oct 08, 2001
Posts: 18
this is taken from JLS.
a narrowing primitive conversion may be used if all of the following conditions are satisfied:
1.The expression is a constant expression of type byte, short, char or int.
2.The type of the variable is byte, short, or char.
3.The value of the expression (which is known at compile time, because it is a constant expression) is representable in the type of the variable.
If the type of the expression cannot be converted to the type of the variable by a conversion permitted in an assignment context,
then a compile-time error occurs.
since all three conditions are met, narrowing conversion is possible in this case without explicit cast.
hope thid helps.
I agree. Here's the link:
subject: Narrowing conversion
jQuery in Action, 3rd edition