Java Increment and Decrement Operator

In this chapter you will learn:

  1. When to use Increment and Decrement Operator
  2. Different between Increment and Decrement Operator
  3. Example - increment operator

Description

++ and -- are Java's increment and decrement operators. The increment operator, ++, increases its operand by one. The decrement operator, --, decreases its operand by one.

DIfference

For example, this statement:


x = x + 1;

can be rewritten like this by use of the increment operator:


x++;

This statement:


x = x - 1;

is equivalent to


x--;

The increment and decrement operators are unique in that they can appear both in postfix form and prefix form. In the postfix form they follow the operand, for example, i++. In the prefix form, they precede the operand, for example, --i.

The difference between these two forms appears when the increment and/or decrement operators are part of a larger expression. In the prefix form, the operand is incremented or decremented before the value is used in the expression. In postfix form, the value is used in the expression, and then the operand is modified.

The following table summarizes the difference between Pre-and Post- Increment and Decrement Operations:

Initial Value of xExpressionFinal Value of yFinal Value of x
5 y = x++ 5 6
5 y = ++x 6 6
5 y = x-- 5 4
5 y = --x 4 4

For example:


x = 42; 
y = ++x;

y is set to 43, because the increment occurs before x is assigned to y. Thus, the line


y = ++x;

is the equivalent of these two statements:


x = x + 1; 
y = x;

However, when written like this,


x = 42; 
y = x++;

the value of x is obtained before the increment operator is executed, so the value of y is 42.

In both cases x is set to 43. The line


y = x++;

is the equivalent of these two statements:


y = x; 
x = x + 1;

Example

The following program demonstrates the increment operator.

 
public class Main {
/*  w ww. j  av a 2  s  .  c  o m*/
  public static void main(String args[]) {
    int a = 1;
    int b = 2;
    int c = ++b;
    int d = a++;

    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("c = " + c);
    System.out.println("d = " + d);

  }
}

The output of this program follows:

Next chapter...

What you will learn in the next chapter:

  1. What are Java Boolean Logical Operators
  2. Logical Operator List
  3. True table
  4. Example - boolean logical operators
  5. How to use the Bitwise Logical Operators
Home »
  Java Tutorial »
    Java Langauge »
      Java Operator
Java Arithmetic Operators
Java Compound Assignment Operators
Java Increment and Decrement Operator
Java Logical Operators
Java Logical Operators Shortcut
Java Relational Operators
Java Bitwise Operators
Java Left Shift Operator
Java Right Shift Operator
Java Unsigned Right Shift
Java ternary operator