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
Release: 2024-12-14 01:56:10
Original
886 people have browsed it

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
Copy after login

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'
Copy after login
  • Add an empty String at the beginning:
"" + 'a' + 'b'
Copy after login
  • Use a StringBuilder or String.format:
new StringBuilder().append('a').append('b').toString()
String.format("%c%c", 'a', 'b')
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template