Thursday, 7 January 2016

Java Program to Demonstrate Postfix and Prefix Increment and Decrement Operators

Postfix and Prefix Increment and Decrement Operators in Java

Difference between Postfix and Prefix versions of ++ & -- Operators.


               There isn't much difference between the prefix and postfix form. However, when it comes larger expressions, it makes significant difference. 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 the use in the expression and then the operand is changed. The following program shows the significance in a simple form.

Program


// simple java program to Demonstrate Postfix and Prefix Operation in Java

public class PrefixPostfixDemonstration {
    public static void main(String[] args){
        int i = 3;
        i++;
        System.out.println(i);    // "4"
        ++i;                     
        System.out.println(i);    // "5"
        System.out.println(++i);  // "6"
        System.out.println(i++);  // "6"
        System.out.println(i);    // "7"
    }

}

Output

4
5
6
6
7

Note: In the above program, ++i increments 5 to six and print as 6 on the same line. The i++ prints 6 on the line and increment the value to 7, which is used in the next line. 

No comments :

Post a comment