Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't you add an int and a char in some cases?

Tags:

java

Why does

char ch = '4'; ch = '4' + 2; 

work, but

char ch = '4'; ch = ch  + 2; 

doesn't?

like image 576
Lester Avatar asked Jul 07 '14 10:07

Lester


People also ask

Can you add int to char?

In Java, char and int are compatible types so just add them with + operator. char c = 'c'; int x = 10; c + x results in an integer, so you need an explicit casting to assign it to your character varaible back.

What happens when you add a character and an integer in c?

When you add a char to an int , the (p)r-value created is promoted to an int . Therefore what is printed is the int equivalent to the sum of the (usually) ASCII value + the int.

What happens when we add char and int in java?

If it's a char, then the first line will give me an error and the second one will not. If it's an int, then the opposite will happen.

What happens when you bring a char value into an int variable?

If we direct assign char variable to int, it will return the ASCII value of a given character. If the char variable contains an int value, we can get the int value by calling Character. getNumericValue(char) method.


1 Answers

To understand this, lets consider what the compiler does at each step for both possibilities. Lets start with:

ch = '4' + 2; 

The compiler converts '4' to an int. So it becomes

ch = 52 + 2; 

Which the compiler then turns into

ch = 54; 

ch is a char, and the compiler is allowed to convert 54 to a char as it can prove that there is no loss in the conversion.

Now lets consider the second version:

ch = ch  + 2; 

ch has no known value at compile time. Thus this becomes

ch = ((int) ch) + 2; 

Now the compiler cannot prove that the result of this (an int) is storable within the range of a char. So it will not automatically narrow it, and reports it as an error.

EDIT1:

If the compiler can prove that the variable will never change, and is inlineable. Then the second form can be turned into the first. Subir pointed out that adding 'final' makes this possible. Although if a compiler was to perform change analysis then it is technically capable of figuring this out without the final keyword, but final does make it easier for the compiler and readers of the code.

EDIT2:

Narrowing of int to char is covered in the Java Language Spec, the link was kindly provided by Jon Skeet.

like image 174
Chris K Avatar answered Oct 08 '22 11:10

Chris K