Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Subtraction assignment operator (-=)

The -= operator subtracts the right operand from a variable's value and stores the result in that same variable.

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

Syntax

variable -= expression;

variable -= expression; combines subtraction with assignment. The left side must designate a modifiable numeric variable, such as a local variable, field, or array element. The operator does not subtract strings.

For a primitive numeric type T, E1 -= E2 corresponds to E1 = (T) ((E1) - (E2)), except that E1 is evaluated only once. Its previous value is saved before the right side is evaluated.

The implicit conversion can lose data. Thus, byte count = 10; count -= 3; is valid, whereas a subsequent count = count - 3; requires a cast. Integer overflow does not throw an exception.

Examples

public class Main {
    public static void main(String[] args) {
        int balance = 20;
        balance -= 7;
        System.out.println(balance);

        byte count = 10;
        count -= 3;
        System.out.println(count);
    }
}

Result

13
7

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