Home  >  Article  >  Java  >  How to write addition in java

How to write addition in java

下次还敢
下次还敢Original
2024-04-28 23:12:12508browse

In Java, the addition operator ( ) can be used to add two numbers or concatenate two strings. For numeric types, performs numerical addition, and for string types, is used to concatenate strings. It should be noted that if the operand types are different, Java will automatically perform type conversion and convert the result to a larger type.

How to write addition in java

Addition operation in Java

In Java, the addition operator is used to combine two numbers or characters Add strings.

Numerical addition

For numeric values, the addition operator is . For example:

<code class="java">int a = 5;
int b = 10;
int sum = a + b; // sum 等于 15</code>

String addition

For strings, the addition operator is used to concatenate two strings. For example:

<code class="java">String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // fullName 等于 "John Doe"</code>

Type conversion

If the addition operand types are different, Java will automatically perform type conversion. For example:

<code class="java">int a = 5;
double b = 3.14;
double sum = a + b; // sum 等于 8.14</code>

Other Notes

  • If you add a null value to a string, it will be converted to a "null" string.
  • If a number is added to a null value, a NullPointerException is thrown.
  • "==" is used to compare two values ​​for equality, while " " is used for addition.

The above is the detailed content of How to write addition in java. 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