Java - Increment (++) and Decrement (--) Operators

What are Increment (++) and Decrement (--) Operators?

The increment operator (++) increments a variable of numeric data type value by 1.

The decrement operator (--) decrements the value by 1.

The rules on increment operator ++ can be applied to decrement operator --.

Increment ++ Operators

In the following code,

  
int i = 100; 

To increment the value of i by 1, you can use one of the four following expressions:

  
i = i + 1; // Assigns 101 to i 
i += 1;    // Assigns 101 to i 
i++;       // Assigns 101 to i 
++i; 
  

The increment operator ++ can be used in a more complex expression as

int i = 1; 
int j = 5; 
j = i++ + 1;  

Demo

public class Main {
  public static void main(String[] args) {
    int i = 1; //from w ww  . j  a v  a2  s. com
    int j = 5; 
    j = i++ + 1;  

    System.out.println(j);
  }
}

Result

two kinds of increment/decrement operators

There are two kinds of increment/decrement operators:

  • Post-fix increment operator, for example, i++. When ++ appears after its operand, it is called a post-fix increment operator.
  • Pre-fix increment operator, for example, ++i. When ++ appears before its operand, it is called a pre-fix increment operator.

The post-fix increment uses the current value of its operand first, and then increments the operand's value.

The pre-fix increment increments the operand's value, then uses the current value of its operand first,

Demo

public class Main {
  public static void main(String[] args) {
    int i = 1; /*from www  .j  a v  a 2  s . c om*/
    int j = 0; 
    j = i++ + 1;  
    System.out.println(j);
    System.out.println(i);
    
    i = 1; 
    j = 0;
    j = ++i + 1;   
    System.out.println();
    System.out.println(j);
    System.out.println(i);
  }
}

Result

Related Topics

Quiz