The following line of Java code produce error.
Even though datatypes in java are signed?
char c = -128;
The following line of Java code produce error.
Even though datatypes in java are signed?
char c = -128;
Char is the one data type that isn't signed in java. Its a 16 bit unsigned integer.
Straight from the Oracle tutorial for Java datatypes.
char
: Thechar
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).
this is because -128 is int. you need to cast to char. please be aware that char is unsigned type, so after
char c = (char) -1;
System.out.print(Integer.valueOf(c).toString());
you will get 65535
It has a minimum value of '\u0000' (or 0)
and a maximum value of'\uffff' (or 65,535 inclusive)
.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
As per Oracle Java doc
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).
Therefore, you cannot really assign negative values to char
and char c = -128
will result in error.
When you try to assign negative values to a char and type-cast it , it will rotate that value through the other (max) end.
char c;
c = (char) 65; // 'A'
c = (char) -100; // 'ワ' and it results in 65,535(inclusive) - 100 = (char) 65,436
c = (char) 65436; // 'ワ'
int i;
i = (char) 65; // 65
i = (char) -1; // 65535 : notice how the char value cycles through the other end
i = (char) -100; // 65436 : same as (char) -100. Here, int returns 65,436.
Cast it:
char c = (char) -128;
Though this will probably not behave like you expect. Perhaps a byte would be better?
If you ever find yourself confused about min or max values of primitives, find their object equivalent and look for the MIN_VALUE or MAX_VALUE constant. Eg:
http://docs.oracle.com/javase/6/docs/api/java/lang/Character.html#MIN_VALUE
char holds 16 bit unsigned value.We can assign integer to char but positive upto 2 raise to the power 16 which is 65536-1 as we start from 0.
if we need to assign -ve values that some of the bit will be loose and we will need to typecast.In this situation compiler will store the sign bit along with the actual value and the last bits will be dropped. char c=(char) -128 will not give compile error but you will get absurd results
You can also check whether an int value is valid as a character code by using Character.isValidCodePoint(int codePoint)
method:
boolean isValid = Character.isValidCodePoint(-128); // false