File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Assignment" Watch "Assignment" New topic
Author

Assignment

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: 14074
    
  16

Note: Please quote your sources.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
wood burning stoves
 
subject: Assignment
 
Similar Threads
Type Casting.
Switch / case variable type
Arithmetic Promotion. What's the deal here?
implicit casting of final int to byte ???
Primitive variable declaration doubts