Numeric Type Conversion in Java Char Addition
When adding two Java chars, such as 'a' 'b', a numeric type conversion occurs. Unlike most other programming languages, this addition does not result in a char output.
Result Datatype
According to the Java Language Specification, the result of adding chars, shorts, or bytes is an int. This behavior is attributed to Java's binary numeric promotion rules, which state that both operands are converted to type int when performing binary arithmetic operations.
Example
Consider the following example:
char x = 'a' + 'b'; // 결과는 int System.out.println(x); // 195를 출력
Exceptions
However, these rules have an exception for compound assignment operators like =. For instance:
char x = 1, y = 2; x += y; // 합법적이며 결과는 char System.out.println(x); // 195를 출력하고 컴파일 오류가 발생하지 않음
In this case, the result of the addition (an int) is explicitly cast back to char using a compound assignment operator.
Determining the Result Type
To determine the type of the result in general, one can cast it to an Object and query its class:
System.out.println(((Object)('a' + 'b')).getClass()); // class java.lang.Integer를 출력
Performance Considerations
Note that the Java bytecode does not have specific instructions for arithmetic with smaller data types. Instead, it uses int-based instructions (e.g., iadd) and manually zeroes the upper bytes if necessary.
String Concatenation
If the intent is to concatenate characters as a String, not interpret them numerically, use an empty String in the expression, as adding a char and a String results in a String.
The above is the detailed content of Why Does Adding Two Java Chars Result in an Integer, Not a Char?. For more information, please follow other related articles on the PHP Chinese website!