File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Char size and usage Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Char size and usage" Watch "Char size and usage" New topic

Char size and usage

Eric Lidell

Joined: Jul 02, 2003
Posts: 20
i am able to use char c=(char)2147483647;
where 2147483647 is the max size of an int.
anything more than that throws an compile time error.
however the size of a char is 2 bytes and its the maximum int value is around 65535.
how is char variables able to hold values from 65535 to 2147483647 which exceeds its size?
the same is not applicable to int which is of size 32 bits and cant hold a value greater than
2147483647 inspite of casting int x=(int)2147483647.

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

char can't hold a value greater than 65535. If you cast a value greater than that to a char, the high-order bits are truncated -- i.e.,

c is assigned the value 0 (65536 & 0xFFFF is 0.)
The reason you get a compiler error with numbers larger than Integer.MAX_VALUE is that to write a larger integral literal in Java, it must be a long -- you have to write 2147483648L. But you can write
and as it turns out, c will be 0 here as well (all the low-order bits of this number are 0.)
[ July 18, 2003: Message edited by: Ernest Friedman-Hill ]

[Jess in Action][AskingGoodQuestions]
Eric Lidell

Joined: Jul 02, 2003
Posts: 20
Hi Ernest,
Thank for the answer.
I agree. Here's the link:
subject: Char size and usage
It's not a secret anymore!