learn java
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Assignment Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assignment" Watch "Assignment" New topic


Akhil Maharaj
Ranch Hand

Joined: Sep 29, 2007
Posts: 63
Hi ,

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

Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
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;")

SCJP 5.0
Akhil Maharaj
Ranch Hand

Joined: Sep 29, 2007
Posts: 63
Thanks for the quick reply.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14667

Note: Please quote your sources.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Don't get me started about those stupid light bulbs.
subject: Assignment