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

Narrowing conversion

 
Rashmi Tambe
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

then
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...
Rashmi
[This message has been edited by Rashmi Gunjotikar (edited November 28, 2001).]
 
kinnu jemmy
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
kinnu
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic