Home > Java > javaTutorial > body text

How to write addition in java

下次还敢
Release: 2024-04-28 23:12:12
Original
463 people have browsed it

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!