• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Cast

 
Ranch Hand
Posts: 94
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ?.
 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic