Anj
Anj

Reputation: 135

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"

Upvotes: 2

Views: 86

Answers (3)

Vitthal Kavitake
Vitthal Kavitake

Reputation: 879

When using 9 + '0', compiler uses ASCII value of character and adds it to the literal (9) value and then converts it back to the char i.e.

9 + 48 = 57
57 ACII -->= '9' (char)

When using k + '0' k is declared as int and '0' is char. Compiler wont compile here as they are different types and target is smaller to accommodate the resultant value.

Upvotes: -1

Andy Turner
Andy Turner

Reputation: 140494

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.

Upvotes: 1

VGR
VGR

Reputation: 44414

The compiler knows that 9 + '0' is 57, which fits into a 16-bit char value. The compiler does not keep track of variable assignments (except for static final constants) so it cannot be certain that k + '0' evaluates to a value that fits in 16 bits.

That 16-bit size limitation is also why you will also get the same compiler error for this:

char ch = 10_000_000 + '0';

Upvotes: 1

Related Questions