Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Increment operator ++

The ++ operator adds 1 to a variable's value. Prefix ++count produces the new value, while postfix count++ produces the previous value; both store the result in the variable.

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

Syntax

++variable
variable++

The ++ operator adds 1 and stores the result in a variable. Prefix ++count produces the new value; postfix count++ produces the value before the store. The store happens during expression evaluation, not at the end of the statement. Standalone count++; and ++count; have the same effect.

The operand must be a modifiable variable of a numeric type or its corresponding wrapper type; fields and array elements also qualify. Literals, computation results, boolean, and final variables are not allowed. The expression's type remains the variable's type; necessary narrowing and boxing happen implicitly. Unboxing null causes NullPointerException.

Integer overflow does not throw an exception. In the example, before receives 4, leaving count at 5; then ++count stores and produces 6, which is assigned to after. For readability, separate increments from complex calculations.

Examples

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

Result

before=4
after=6
count=6

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