Home > Blockchain >  Java char addition (char1 = char2 10) [duplicate]
Java char addition (char1 = char2 10) [duplicate]

Time:09-22

Why can't i do this?

public class test123 {
    public static void main (String [] args) {
        char c = 34;
        char a = c   10;

    }
}

new to java, so sorry if this question is actually stupid.

CodePudding user response:

When you add numbers, they undergo binary numeric promotion. That is, the operands are widened to allow them to be added.

When you add a char to an int, the char is widened to an int, and the result is an int.

As such, you would have to cast the int back to a char:

char a = (char) (c   10);

However, even when adding a char to another char, both are widened to int, and the result is again an int, and so cannot be assigned to a char variable. The rules are basically:

  • If either operand is a double, widen both to double
  • Else, if either operand is a float, widen both to float
  • Else, if either operand is a long, widen both to long
  • Else, widen both to int

So, even if you were adding a byte to a byte, both are widened to int, added, and the result is an int.


The exception to this is if you made c final:

final char c = 34;

In that case, c has a compile-time constant value, so c 10 is a compile-time constant expression. Because it's a compile-time constant expression, the compiler knows its value, and knows that it fits into the range of char; so it would be allowed:

final char c = 34;
char a = c   10;

CodePudding user response:

As per the JLS, int is the narrowest type for arithmetic. Narrower values are widened to int, and the result is int.

You would get the same error even if you coded:

char a = c   c; // error

CodePudding user response:

The Java char is a primitive data type. It is used to declare the character-type like char char1='a'; But you can add an int to a char, but the result is an int - you'd have to cast back to char

char a = 'a';
char b = (char)(a 4);
System.out.println(b);// print "e"
  •  Tags:  
  • java
  • Related