aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes KM Book -Section3.3 (Narrowing conversion between char and short Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "KM Book -Section3.3 (Narrowing conversion between char and short" Watch "KM Book -Section3.3 (Narrowing conversion between char and short" New topic
Author

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

shweta mathur
Ranch Hand

Joined: Sep 23, 2002
Posts: 109
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 ?


--Shweta<br />SCJP 1.4 <br />SCWCD
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
It seems an errata.


SCJP2. Please Indent your code using UBB Code
Samith Nambiar
Ranch Hand

Joined: Mar 14, 2001
Posts: 147
consider this example:

HTH
/SAmith
Vijay Albuquerque
Ranch Hand

Joined: Feb 17, 2002
Posts: 42
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 !!!


Vijay Albuquerque
SCJP 1.4, SCWCD 1.3
shweta mathur
Ranch Hand

Joined: Sep 23, 2002
Posts: 109
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

Joined: Feb 17, 2002
Posts: 42
I tried the following code and it compiled fine:

No explicit casts needed.
I suggest you check the errata listing on the Book !!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: KM Book -Section3.3 (Narrowing conversion between char and short