Engineering Full Stack Apps with Java and JavaScript
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.
Below expansions will help you understand these operators well.
a++ expands to
a=a+1;
a-- expands to
a = a-1;
++a expands to
a = a+1;
--a expands to
a = a - 1;
b = a++ expands to
temp = a;
a = a + 1;
b = temp;
b=a-- expands to
temp = a;
a = a - 1;
b = temp;
b=++a expands to
a = a + 1;
b = a;
b=--a expands to
a = a - 1;
b = a;
print(a++)
print(a)
a = a + 1;
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.
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.