0

I am a beginner to java. Today, I was watching the tutorial and I got to know that we can assign integer value to char datatype like:

char a = 65;

and when we print

System.out.print(a);

Then, it will give us character value.

A

Why is it?

I have read that implicit type conversion is also known as widening. But char type is smaller in size than int. Then, why the conversion?

1 Answers1

0

char a = 65; gives A, because each character is associated with number, this is the ASCII code. (66 for B, ...etc)

a char in java takes 2 Bytes (16 bits)

When you try to assign an integer that is less than or equal 0xFFFF to a char variable, its work. But when you try to assign a number greater than that (example char a = 0xFFFF+1;) it gives you an error. The 0xFFFF is the maximum value that 2 bytes can hold.

good luck.

ibra
  • 1,164
  • 1
  • 11
  • 26
  • But, why the implicit type conversion from int to char. According to the definition, it should go from smaller datatype to larger datatype – Tabassum Azmi Sep 06 '20 at 00:52
  • @TabassumAzmi you can refer to the already existing question about converting int (4 bytes) to char with smaller size (2 bytes) : https://stackoverflow.com/questions/50829613/internal-conversion-of-integer-to-char-whose-size-is-smaller – ibra Sep 06 '20 at 01:14