In Java, Is the Result of the Addition of Two Chars an Int or a Char

In Java, is the result of the addition of two chars an int or a char?

The result of adding Java chars, shorts, or bytes is an int:

Java Language Specification on Binary Numeric Promotion:

  • If any of the operands is of a reference type, unboxing conversion
    (§5.1.8) is performed. Then:
  • If either operand is of type double, the
    other is converted to double.
  • Otherwise, if either operand is of type
    float, the other is converted to float.
  • Otherwise, if either operand
    is of type long, the other is converted to long.
  • Otherwise, both
    operands are converted to type int.

But note what it says about compound assignment operators (like +=):

The result of the binary operation is converted to the type of the left-hand variable ... and the result of the conversion is stored into the variable.

For example:

char x = 1, y = 2;
x = x + y; // compile error: "possible loss of precision (found int, required char)"
x = (char)(x + y); // explicit cast back to char; OK
x += y; // compound operation-assignment; also OK

One way you can find out the type of the result, in general, is to cast it to an Object and ask it what class it is:

System.out.println(((Object)('a' + 'b')).getClass());
// outputs: class java.lang.Integer

If you're interested in performance, note that the Java bytecode doesn't even have dedicated instructions for arithmetic with the smaller data types. For example, for adding, there are instructions iadd (for ints), ladd (for longs), fadd (for floats), dadd (for doubles), and that's it. To simulate x += y with the smaller types, the compiler will use iadd and then zero the upper bytes of the int using an instruction like i2c ("int to char"). If the native CPU has dedicated instructions for 1-byte or 2-byte data, it's up to the Java virtual machine to optimize for that at run time.

If you want to concatenate characters as a String rather than interpreting them as a numeric type, there are lots of ways to do that. The easiest is adding an empty String to the expression, because adding a char and a String results in a String. All of these expressions result in the String "ab":

  • 'a' + "" + 'b'
  • "" + 'a' + 'b' (this works because "" + 'a' is evaluated first; if the "" were at the end instead you would get "195")
  • new String(new char[] { 'a', 'b' })
  • new StringBuilder().append('a').append('b').toString()
  • String.format("%c%c", 'a', 'b')

The result of the addition of a char and an int

In java, a char occupies 16 bit in UTF-16 encoding.

G's unicode is U+0047, in binary 0000 0000 0100 1111.

When you sum a char and an int(32 bit), the char will be converted to int by inserting 0 into the begin of its binary representation. So 0000 0000 0100 1111 is converted to 0000 0000 0000 0000 0000 0000 0100 1111(in decimal, 71).

That's why you get 73.

Why do I get a number when I add chars?

You're adding their ASCII values:

'a'+'b' = 97+98 = 195

Adding char and int

You're getting that because it's adding the ASCII value of the char. You must convert it to an int first.

Java char addition (char1 = char2 + 10)

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;

Java - why won't char '+' appear on the console?

chars are implicitly convertible to integers in Java. x + w + y adds their values. The integer value of the character '+' happens to be 43, so you get 3 + 43 + 7 (= 53).

Putting the w into parentheses does not change that, contrary to what you said.

To fix this, make w into a String:

String w = "+";

Why does ('1'+'1') output 98 in Java?

In java, every character literal is associated with an ASCII value which is an Integer.

You can find all the ASCII values here

'1' maps to ASCII value of 49 (int type).

thus '1' + '1' becomes 49 + 49 which is an integer 98.

If you cast this value to char type as shown below, it will print ASCII value of 98 which is b

System.out.println( (char) ('1'+'1') );

If you are aiming at concatenating 2 chars (meaning, you expect "11" from your example), consider converting them to string first. Either by using double quotes, "1" + "1" or as mentioned here .



Related Topics



Leave a reply



Submit