+ Operator

+ Operator

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:

  1. **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 or double), the + operator performs floating-point addition, and the result will be of a floating-point type (float or double).

  2. **If both operands are numeric types (excluding float and double) or one operand is a numeric type and the other is a String, the + operator performs arithmetic addition, and the result will be of a numeric type (promoted to int if necessary).

  3. **If one operand is a String, and the other operand is not a String, the + operator performs string concatenation, and the result will be a String.

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.