It's not a secret anymore!*
The moose likes Beginning Java and the fly likes Cast Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Cast" Watch "Cast" New topic
Author

Cast

geetha nagarajan
Ranch Hand

Joined: Jul 13, 2001
Posts: 94
short s ='a';
System.out.println(s);
The output is 97(guess,the ASCII value of 'a').
Is it right that :Conversions b/w short,char & byte always require explicit cast,even though the value is in range.
Then why is it that this code compiles ?.
Doanh Nguyen
Ranch Hand

Joined: Dec 02, 2000
Posts: 45
The code compiles because it meets 3 rules for narrowing conversion:
1. The right operand is a constant expression of type byte, char, short, int.
2. The left opereand is of type byte, char, or short.
3. Value is in range of the left opereand.
No cast is required if these 3 rules are met.
expired user
Greenhorn

Joined: Dec 13, 2001
Posts: 11
When we cast a data type with a lesser size to a bigger one, explicit cast is required. The reason is that when we convert a bigger date type to a smaller one (Byte Size), the bytes will be eliminated to meet the size if the smaller data type and the value won't be correct.
If u cast a smaller data type to bigger datatype, say an short to integer, the conversion will be automatic as the bytes will fit in and there won't be any change in the values.
And if the values are within the range, there is no need for explicit cast.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Cast
 
Similar Threads
how to assign some numeric values like 1 ... to a short variable ?
Casting during shift operation
Casting
Please explain....!!!!
Short Wrapper Class Question