Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

KM Book -Section3.3 (Narrowing conversion between char and short

 
shweta mathur
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pg 48 Section 3.3 of KM's book says
Narrowing conversion between char and byte(or short) values on assignment always require an explicit cast, even if the value is in the range of the destination datatype.
short val = (short)'a' // value in range of short but explicit cast required.

But the following programs compiles without error.
class Test6 {
public static void main(String[] args) {
short val = 'a'; // working without cast.
}
}
Also the JLS says
a narrowing primitive conversion may be used if all of the following conditions are satisfied:
The expression is a constant expression of type byte, short, char or int.
The type of the variable is byte, short, or char.
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.

JLS doesn't mention any special condition for conversion b/w char and byte.
Can anyone clarify what Khalid Mughal means by this statement ?
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It seems an errata.
 
Samith Nambiar
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
consider this example:

HTH
/SAmith
 
Vijay Albuquerque
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shweta,

The expression is a CONSTANT expression of type byte, short, char or int.


The literal 'a' is a compile-time char constant and hence there is no need for the explicit cast.
It works exactly as the JLS Quote statement !!!
 
shweta mathur
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Vijay & Samith,
But I think u didn't understand my question.
I also agree that it is working as per JLS and compile time constant do not need an explicit cast, but I was not able to understand what Khalid Mughal wants to state by his statement
short val = (short)'a' // value in range of short but explicit cast required.

I think as Jose says it seems some errata in his book.. !!!
 
Vijay Albuquerque
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried the following code and it compiled fine:

No explicit casts needed.
I suggest you check the errata listing on the Book !!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic