1

I'm new to Java and I learned that char in java is actually int, so we can do

char c = 'a';
int i = c; // i =97, which is the ascii index of letter "c"

However, when I tried to convert a char to byte, I obtained the same result:

char c = 'a';
byte b = (byte)c; // b =97

I know that in Java, a char is represented by 2 bytes while a byte is represented by a single byte.

Is this always the case that converts a char to int or to byte gives the same result? Why so then?

Rafael
  • 1,761
  • 1
  • 14
  • 21
  • 1
    check this https://stackoverflow.com/questions/4958658/char-into-byte-java – A Paul Jan 17 '21 at 08:54
  • Because in Java "Converting a byte to a char is considered a special conversion." I think this is a good explanation https://stackoverflow.com/questions/4958658/char-into-byte-java – vincenzopalazzo Jan 17 '21 at 08:55
  • To be specific, `char` is a character type in Java and is a unsigned 16-bit type having a range of 0 to 65,535. The purpose of `char` is to represent characters. `char` is indeed part of the integral types in Java and even though it defines characters from the Unicode set which allow for arithmetic manipulations, it represents _characters_ where the others (byte, short, int, long) were meant for numeric types. – Tanner Dolby Jan 17 '21 at 08:55

0 Answers0