1

I've been wondering about the reason why in Java we can assign an integer number directly to a char variable:

char a = 6;

but we can't assign an integer without a type cast

int bInt = 6;
char b = bInt; // error, cast first

I do understand that char is just 16-bit unsigned integer in the background, and that generally if we want to move a value from a wider range type to a lower range one, type cast needs to be explicit. But why is that not the case in the first example, what is the type of the 6 literal ?

Zed
  • 5,683
  • 11
  • 49
  • 81
  • 4
    `char a = 6;`: `6` is a compile-time constant. So the compiler knows for certain that it's within the char range. – ernest_k Jun 18 '19 at 13:44
  • Try assigning character like `70000` and you will see that compiler will complain. It doesn't for `6` because it *knows* it is within `char` range (16 bits) but it doesn't have that certainty for *every* value of `int` which could be stored in `bInt` variable. – Pshemo Jun 18 '19 at 13:45
  • Thanks everyone, that make sense. – Zed Jun 18 '19 at 13:46

0 Answers0