Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

The + operator: addition and string concatenation

In Java, + adds numbers or concatenates text when at least one operand has type String. Operand types, numeric promotion, and parentheses determine the result. Unary + preserves the value after type promotion.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

left + right; +value

Binary + adds numeric values. If at least one operand has type String, it performs concatenation instead: the other operand is converted to text. Operators + group from left to right; multiplication has higher precedence. Thus "sum=" + 7 + 5 produces "sum=75", while "sum=" + (7 + 5) produces "sum=12".

Addition applies numeric promotion: after any unboxing, the result type is double, float, long, or int, according to the first of these types present among the operands. Operands of type byte, short, and char are promoted to at least int, so 'A' + 1 produces 66, not the next character. Unboxing null throws NullPointerException; boolean does not support numeric addition.

Overflow in int and long wraps the result without an exception. Assignment to long does not prevent earlier overflow when adding two int values: use, for example, (long) a + b. Addition with float and double can introduce rounding errors.

Unary +value does not add a second operand: it preserves the value after numeric promotion; for example, +a has type int when a has type byte. The expression a + b alone does not modify its operands; ++ and += are separate operators.

Examples

public class AdditionDemo {
    public static void main(String[] args) {
        byte a = 7;
        byte b = 5;
        int sum = a + b;
        System.out.println(sum);
        System.out.println("sum=" + a + b);
        System.out.println("sum=" + (a + b));
        System.out.println('A' + 1);
        System.out.println(Integer.MAX_VALUE + 1);
    }
}

Result

12
sum=75
sum=12
66
-2147483648

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources