I am confused with byte and char in Java. I have the following program segment :
byte b = 65;
char c = 65;
short s = 65;
System.out.println("b:"+b+" c:"+c+ " s:"+s); // outputs b:65 c:A s:65
The bit representation of b, c and s are same they all are :: 00000000 01000001 .
My question is if the bits are same then how they act differently - b as byte, c as char and s as short ?
Another question is : char c = 65; why this is a correct statement ? it does not give error though I am assigning int value to a char.
Thanks.
how they act differently ?
Refer the JLS:
The integral types are byte, short, int, and long, whose values are 8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively, and char, whose values are 16-bit unsigned integers representing UTF-16 code units.
The values of the integral types are integers in the following ranges:
For byte, from -128 to 127, inclusive
For short, from -32768 to 32767, inclusive
For int, from -2147483648 to 2147483647, inclusive
For long, from -9223372036854775808 to 9223372036854775807, inclusive
For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535
Another difference will be their Wrapper Classes differ : byte to Byte , char to Character and short to Short.
char c = 65; why this is a correct statement ?
char, whose values are 16-bit unsigned integers representing UTF-16 code units (§3.1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With