• Post Reply Bookmark Topic Watch Topic
  • New Topic

Working with Java Data Types  RSS feed

 
Urs Waefler
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the code: Line 2 and line 3 are not valid; I do not understand. This is perfectly legal: How do you explain that line 2 and line 3 are not legal?
 
Ivan Pronin
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The char and short, each takes 2 byte of memory. Assignment of short to char requires explicit casting as short can take negative values also but char does not.
 
Campbell Ritchie
Marshal
Posts: 56529
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To the Java® Language Specification! (=JLS) Beware: the JLS can be very difficult to read. What are defined as widening conversions can be done without an explicit cast. Changing short→char is not a widening conversion, so it requires an explicit cast.
If you scroll down the page, you will see that char→short is described as a narrowing conversion. A char can store values ≥ 2¹⁵, which a short cannot store. Changing short→char is also a narrowing conversion because as IP says, a short supports values < 0 which cannot fit into a char.
Had you marked the variable s final, it would have become a compile‑time constant; the compiler allows an exception whereby a constant value can be implicitly narrowed from an int to a char, for example. You can try making the variable in line 2 final, too, but you won't get line 3 to compile like that.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!