Adding Numbers and Strings in Java: Understanding the + Operator

Discover how the + operator is used in Java for both addition and string concatenation. Learn the difference between adding numbers and concatenating strings, and understand how Java handles these operations in different contexts.



Adding Numbers and Strings in Java

Warning: Java uses the + operator for both addition and concatenation.

Adding Numbers

If you add two numbers using the + operator, the result will be a number:

int x = 10;
int y = 20;
int z = x + y;  // z will be 30 (an integer/number)

Concatenating Strings

If you use the + operator with strings, they will be concatenated:

String x = "10";
String y = "20";
String z = x + y;  // z will be "1020" (a String)

If you add a number and a string using the + operator, the result will also be a string concatenation:

String x = "10";
int y = 20;
String z = x + y;  // z will be "1020" (a String)

This behavior of the + operator is important to remember when working with Java, as it determines whether the operation results in numeric addition or string concatenation.