Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Assignment

 
Akhil Maharaj
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

Why can not we assign a short or byte to char variable ?

 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer is very simple. The range of char is 0 to 65535, whereas the range of byte is -128 to 127 and the range of short is -32768 to 32767. Since char cannot hold negative values, you may not get the expected result when you assign a negative byte or short value to a char variable. This is why Java refuses to let you perform the assignment without an explicit cast (e.g. "short s = -128; char c = (char)s;")
 
Akhil Maharaj
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the quick reply.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Pie
Posts: 15436
41
Android IntelliJ IDE Java Scala Spring
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic