Skip to main content

Operators

Pre And Post-Unary Operators

Unary operators are operators that require only one operand to perform their operation. They are frequently utilized in programming languages to execute various operations, such as incrementing or decrementing a value.

Pre and Post unary operators differ in when they apply their operation relative to the operand.

Pre unary operator

Pre increment (++var)

In pre-increment, the variable's value is incremented before the value is used in the expression.

int a = 10;
System.out.println(++a); // 11
  • Increments the value of the variable a by 1.
  • Prints the value of the variable a after it has been incremented.

Pre decrement (--var)

In pre-decrement, the variable's value is decremented before the value is used in the expression.

int a = 10;
System.out.println(--a); // 9
  • Decrements the value of the variable a by 1.
  • Prints the value of the variable a after it has been decremented.

Post unary operator

Post increment (var++)

In post-increment, the value of the variable is incremented after the value is used in the expression

int a = 10;
System.out.println(a++); // 10
  • Prints the value of the variable a before it is incremented.
  • Then increments the value of the variable a by 1.

Post decrement (var--)

In post-decrement, the value of the variable is decremented after the value is used in the expression

int a = 10;
System.out.println(a--); // 10
  • Prints the value of the variable a before it is decremented.
  • Then decrements the value of the variable a by 1.