Adding Java Chars: Int or Char Outcome?
When adding two chars ('a' 'b') in Java, it may seem surprising that the result is an int (195). This is due to Java's binary numeric promotion rules.
Binary Numeric Promotion
According to the Java Language Specification, when adding Java chars, shorts, or bytes, the result is promoted to an int. This is designed to avoid any loss of precision when working with smaller data types.
Special Case: Compound Assignment
However, there is an exception for compound assignment operators like =. In this case, the result of the operation is converted to the type of the left-hand variable.
Determining the Result Type
One way to determine the type of the result is to cast it to Object and check its class:
System.out.println(((Object)('a' + 'b')).getClass()); // Outputs: class java.lang.Integer
Char Concatenation
If you intend to concatenate chars as a String rather than an int, there are various ways to do so:
'a' + "" + 'b'
"" + 'a' + 'b'
new StringBuilder().append('a').append('b').toString() String.format("%c%c", 'a', 'b')
The above is the detailed content of Why Does Adding Two Java Chars Result in an Integer?. For more information, please follow other related articles on the PHP Chinese website!