Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte, char, int in Java - bit representation

Tags:

java

char

byte

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.

like image 510
Ronin Avatar asked Feb 01 '26 21:02

Ronin


1 Answers

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:

  1. For byte, from -128 to 127, inclusive

  2. For short, from -32768 to 32767, inclusive

  3. For int, from -2147483648 to 2147483647, inclusive

  4. For long, from -9223372036854775808 to 9223372036854775807, inclusive

  5. 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).

like image 127
AllTooSir Avatar answered Feb 03 '26 10:02

AllTooSir