Home >Java >javaTutorial >Why Does Adding Two Java Chars Result in an Integer?

Why Does Adding Two Java Chars Result in an Integer?

Barbara Streisand
Barbara StreisandOriginal
2024-12-14 01:56:10891browse

Why Does Adding Two Java Chars Result in an Integer?

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:

  • Add an empty String:
'a' + "" + 'b'
  • Add an empty String at the beginning:
"" + 'a' + 'b'
  • Use a StringBuilder or String.format:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn