Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Subtraction operator (-)

The binary - operator subtracts its right operand from its left operand. Learn numeric promotion, grouping, and integer overflow when subtracting values in Java SE 21.

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

Syntax

left - right

The operator left - right computes the difference between two numeric values; it does not itself modify its operands. It does not support String or boolean. Binary subtraction differs from unary -value, which negates a value.

Before calculating, Java applies binary numeric promotion: it selects double if either operand is double; otherwise, it selects float, long, or int, in that order. Consequently, subtracting two byte, short, or char values produces an int. Wrapper objects are unboxed; unboxing null throws NullPointerException.

The operator has the same precedence as +, below *, /, and %. It groups left to right: 20 - 7 - 2 means (20 - 7) - 2. Parentheses can change the grouping.

Overflow in int or long subtraction wraps the result without an exception; Integer.MIN_VALUE - 1 produces 2147483647. Calculations with float and double can involve rounding and produce infinity or NaN. The example demonstrates promotion from byte to int, grouping, and overflow.

Examples

public class Main {
    public static void main(String[] args) {
        byte total = 20;
        byte used = 7;
        int remaining = total - used;
        System.out.println(remaining);
        System.out.println(20 - 7 - 2);
        System.out.println(20 - (7 - 2));
        System.out.println(Integer.MIN_VALUE - 1);
    }
}

Result

13
11
15
2147483647

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