
class IncrementDecrementDemo{
public static void main (String… args){
int myValue = 10;
//Increments by 1, myValue becomes 11
myValue++;
System.out.println("Incremented value: " + myValue);
//Decrements by 1, myValue becomes 10
myValue--;
System.out.println("Decremented value: " + myValue);
}
}
These operators can be applied as a prefix (before the variable’s name) or a postfix (after the variable’s name); the position of it may affect the obtained result.

The following program shows an example of it
class PrefixExample{
public static void main(String[] args){
int num1 = 10;
int num2 = 20;
int result = ++num1 + num2; // result = 31
System.out.println(result);
}
}
When the increment/decrement operators are used before the variable’s name, the value will be incremented/decremented before any other expression in the given statement, and its result will be used in those expressions.

Let’s see now what happens if we modify our program to use the postfix version of the increment operator
class PostfixExample{
public static void main(String[] args){
int num1 = 10;
int num2 = 20;
int result = num1++ + num2; // result = 30
System.out.println(result);
}
}
When the increment/decrement operators are used after the variable’s name, the value will be incremented/decremented after all the expressions in the given statement, thus its result won’t be used in those expressions.

If you’re using the increment/decrement operator alone, it doesn’t matter the position of the operator. So, in the following code, it really doesn’t matter the position in which we use the operator.
class IncrementExample{
public static void main(String...args){
int num1 = 10;
int num2 = 20;
num1++; // ++num1 will produce the same result here
int result = num1 + num2; // result = 31
System.out.println(result);
}
}
Simple, right? Test your increment/decrement knowledge with our quiz.
Decrement Increment Java postfix prefix programming Unary Operators