Java Arithmetic Operators Increment and Decrement Operator

Introduction

The ++ and the -- are Java's increment and decrement operators.

The increment operator increases its operand by one.

The decrement operator decreases its operand by one.

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--;                                                                                                 

Java Increment and Decrement Operator can appear in postfix form and prefix form.

In postfix form, they follow the operand.

In prefix form, they precede the operand.

In the prefix form, the operand is incremented or decremented before the value is obtained for use in the expression.

In postfix form, the previous value is obtained for use in the expression, and then the operand is modified.

For example:

x = 42;  
y = ++x; 

In the code above, 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.

Here, the line y=x++; is the equivalent of these two statements:

y = x;  
x = x + 1; 

The following program demonstrates the increment operator.

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

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



PreviousNext

Related