Table of contents
Introduction
In Java, the +
operator does not always return an int
for numbers. Rather, it behaves differently depending on the data types of the operands involved:
**If both operands are numeric types (e.g.,
byte
,short
,int
,long
,float
,double
), and at least one of them is a floating-point type (float
ordouble
), the+
operator performs floating-point addition, and the result will be of a floating-point type (float
ordouble
).**If both operands are numeric types (excluding
float
anddouble
) or one operand is a numeric type and the other is aString
, the+
operator performs arithmetic addition, and the result will be of a numeric type (promoted toint
if necessary).**If one operand is a
String
, and the other operand is not aString
, the+
operator performs string concatenation, and the result will be aString
.
Here are examples illustrating these behaviors:
// Numeric addition
int a = 10;
int b = 20;
int sum = a + b; // Result: 30
// Floating-point addition
float x = 10.5f;
float y = 20.5f;
float total = x + y; // Result: 31.0
// Numeric addition with promotion to int
byte byteValue1 = 10;
byte byteValue2 = 20;
int result = byteValue1 + byteValue2; // Result: 30
// String concatenation
String str1 = "Hello ";
String str2 = "World";
String message = str1 + str2; // Result: "Hello World"
So, the behavior of the +
operator in Java depends on the types of its operands, and it may return different types of results accordingly.