Increment or Decrement integers in apex

To increase or decrease numeric values in apex, the increment (++) and decrement (--) operators can be used. These operators increase or decrease the numeric value by one .

The position of the operator (before or after the variable) determines when the value is updated during execution.

OperatorUsageExample
Increment (++)Increase the value by one and it can be used after the variable.
Integer x = 5;

x++; // x becomes 6 (after increment)
Decrement (--)Decrease the value by one and it can be used after the variable.
Integer x = 5;

x--; // x becomes 4 (after decrement)
Increment (++)Increase the value by one and can be used before the variable.
Integer x = 5;

++x; // x becomes 6 (before using)
Decrement (--)Decrease the value by one and can be used before the variable.
Integer x = 5;

--x; // x becomes 4 (before using)

The increment and decrement operators are commonly used in loops and conditional statements.

The following example shows how to increment a variable value before and after it is used.

Loading...

In the above example:

  • The variables count, currentCount, items, newItems are Integer variables.
  • The operator ++ on count variable, increment the value of count by one before it is assgined to currentCount.
  • The operator ++ on items variable, increment the value of count by one after it is assgined to newItems.

Try It Yourself

Loading...