Prefix and Postfix operators in Java

The unary operator '++expr' is a prefix operator and 'expr++' is a postfix operator.

When used in a assignment or print context (like within a print statement), a prefix operator (e.g. ++a) first increments a and then return the value of a, whereas the postfix operator (e.g. a++) returns the value of a and then increments a.

 

Expansions for the prefix and postfix shorthand forms

Below expansions will help you understand these operators well.

  1. a++ expands to

    • a=a+1;

  2. a-- expands to

    • a = a-1;

  3. ++a expands to

    • a = a+1;

  4. --a expands to 

    • a = a - 1;

  5. b = a++ expands to

    • temp = a;

    • a = a + 1;

    • b = temp;

  6. b=a-- expands to

    • temp = a;

    • a = a - 1;

    • b = temp;

  7. b=++a expands to

    • a = a + 1;

    • b = a;

  8. b=--a expands to

    • a = a - 1;

    • b = a;

  9. print(a++)

    • print(a)

    • a = a + 1;

  10. print(++a)

    • a = a + 1;

    • print(a);

 

Note: Ones that use temp can be very tricky to solve. Refer to this question and try to answer: http://javajee.com/javaquizzes/question-49.

 

Example: prefix and postfix operator

int a=4;

System.out.println(a--);

System.out.println(--a);

System.out.println(a);

This will print:

4

2

2

  • The variable 'a' is assigned 4 initially.

  • First println with a-- prints the value of a and then decrements a to 3. So 4 is printed first.

  • Second println with --a first decrements a and then prints a, so value is now 2 and 2 is printed.  

  • Last println prints the current value of a, which is 2.

Search the Web

Custom Search

Searches whole web. Use the search in the right sidebar to search only within javajee.com!!!