Anjani Anjani - 16 days ago 5
Java Question

Implicit variable casting

How come this,

char ch = 9 + '0';
System.out.println(ch);


Will result in,

9


But,

int k = 9;
char ch = k + '0';
System.out.println(ch);


will return

"Type mismatch: cannot convert from int to char"

Answer

This is described in JLS Sec 5.2:

5.2 Assignment Contexts

...

if the expression is a constant expression (ยง15.28) of type byte, short, char, or int:

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

...

Example: The compile-time narrowing of constant expressions means that code such as:

byte theAnswer = 42;

is allowed.

This applies to your example because 9 + '0' is a constant, and it can be statically determined that it fits into a char. As such, the cast can be done implicitly.

On the other hand, k is not constant, so the compiler can't know for sure that k + '0' will fit into char; hence, it requires an explicit cast.

Comments