Why can I generate char beyond max value?

1.9k Views Asked by At

Why does the following code not generate an error?

System.out.println((char) 2147483647);

According to oracle datatypes, the maximum size for a char is 65,535.

  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
5

There are 5 best solutions below

2
On BEST ANSWER

Why can I generate char beyond max value?

2147483647 is not a char but an int.

You're not assigning an invalid value to a char, you're casting a valid int to char and then Narrowing Primitive Conversion rules apply. See Java specs: §5.1.3.

In short you keep lowest 16 bits of original integer ("A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T.").

Why does the following code not generate an error?

Because it's not an error, it's a well-defined behavior.

3
On

Actually, the answer to your question is you can't.

Why you dont see any error?
Because Character.MAX_VALUE + 1 = Character.MIN_VALUE... Same as Integer.MAX_VALUE and others, JVM treats it as a loop to avoid this kind of problems... but gives false results when try to calculate....

Check this question for further and technical info

1
On

This works with any data type, it's called an integer overflow and when casting any bits beyond the size of the type you're casting to are cut off.

0
On

You do a narrowing conversion from int to char, which is allowed see java spec: 5.1.3. Narrowing Primitive Conversion:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

The resulting char isn't larger than Character.MAX_VALUE. The compiler converts (char) 2147483647 to 65535

0
On

char is a 16bit data type to which a numeric value can be casted to.

When you cast a 32bit integer to a 16bit short (or to char) you loose the upper bits of your source.

Int32 i = 2147483647; // 0x7FFFFFFF
Int16 s = (Int16) i;  //     0xFFFF (65535)
char  c = (char)  i;  //     0xFFFF (65535)