How to use Java increment operator (++) and decrement (--) operator. - Java Language Basics

Java examples for Language Basics:Operator

Introduction

Java increment operator ++ increases its operand's value by one while decrement operator -- decreases its operand's value by one.

Increment and decrement operators can be used in two ways, postfix (as given in above example) and prefix.

If prefix form is used, operand is incremented or decremented before substituting its value.

If postfix form is used, operand's old value is used to evaluate the expression.

Demo Code

 
public class Main {
 
        public static void main(String[] args) {
                 int i = 10;
                 int j = 10;
                 // www  . ja  v a 2s. com
                 i++;
                 j++;
                 
                 System.out.println("i = " + i);
                 System.out.println("j = " + j);
                 
                  /*
                   * value of i would be assigned to k and then its
                   * incremented by one.
                   */
                  int k = i++;
                 
                  /*
                   * value of j would be incremented first and then
                   * assigned to k.
                   */
                  int l = ++j;
                 
                  System.out.println("k = " + k);
                  System.out.println("l = " + l);
                 
                 
        }
       
}

Result


Related Tutorials