Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Converting from char to short

 
shivaji
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Roberts Heller& ernest book mentions ( Page 108, third paragraph) that char values can not be implicitly converted to short variables.
Yet, I saw an exam question on this mock exam
http://joppa.appliedreasoning.com/javaCert/html/exam.html . This lists a statement short s='s' as a valid conversion statement.This does not work in JDK 1.3.1 . The author mentions that it did not work in 1.2 either - but that was a bug. It seems to work in 1.3.0 and also 1.1.8.
I could not locate any documentation on Sun's site about what conversions are allowed.
Can someone explain why this "feature" seems to work in alternate versions ?
TIA
 
Vikrama Sanjeeva
Ranch Hand
Posts: 760
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes its a Bug! as far as JDK versions are concerned.I remember that it does not work on JDK1.2 But it works on JDK1.3.And remember u are appearing in Java2 that is JDK1.2.
Bye.
Viki.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
short s='s'
I could not locate any documentation on Sun's site about what conversions are allowed.
Can someone explain why this "feature" seems to work in alternate versions ?

Don't count on this working. Even though a short and a char are both 2 bytes, they are not easily casted as one another. The difference is that a char variable is unsigned while a short is signed. Therefore, there are values that are legal chars that are not legal shorts and there are values that are legal shorts that are not legal chars. Therefore, in practice, it is best to explicitly cast from one of these types to the other.
Corey
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
short s = 's';

This is line is a perfectly legal assignement!!!
Although this won't compile:
char c = 's';
short s = c;

this is fine:
short s = 's';
You are assigning a short variable a character *literal*, not a character variable.
You are assigning a numeric type using a character literal, but since the numeric value of the character literal can "fit" into a short, this is allowed. There is a special exception to assignment rules that does allow this implicit narrowing conversion. See JLS 5.2 and this code:

Rob
[ January 10, 2002: Message edited by: Rob Ross ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic