Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Decrement operator --

The -- operator subtracts 1 and stores the result in a variable. The x-- form yields the previous value, whereas --x yields the new value. Both forms update the variable while evaluating the expression.

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

Syntax

x--;
--x;

The -- operator subtracts 1 from a variable's value and stores the result back. The postfix form x-- yields the value before the update; the prefix form --x yields the value after the update. As standalone statements, both have the same effect. In x--, storage does not wait until the end of the statement.

The operand must be a modifiable variable of a numeric type or a wrapper type that can be unboxed to a numeric type. It may be a field or array element. Literals, arithmetic results, final variables, and boolean values are not allowed. The expression has the variable's type, but its result is not itself a variable.

Java applies numeric promotion and, when needed, narrowing and boxing of the result. Thus, byte and char also support --. Integer overflow does not throw an exception; unboxing null causes NullPointerException.

In the example, before receives 5, and x becomes 4. Then --x stores 3, which after also receives. For readability, avoid modifying the same variable repeatedly within one complex expression.

Examples

public class Main {
    public static void main(String[] args) {
        int x = 5;
        int before = x--;
        int after = --x;
        System.out.println("before=" + before);
        System.out.println("after=" + after);
        System.out.println("x=" + x);
    }
}

Result

before=5
after=3
x=3

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