KaiquanMah's picture
b = a++ [add, keep initial a]; ++a [add, get new 'a']
982a68e verified
Let's return to Java's 'expression statements' for a moment.
So far, we have mainly used expression statements
to increase and decrease the value of a variable in a statement,
for example in a 'for statement':
// i++ increases the value of i by one
for (int i=0; i<10; i++) {
System.out.println("i: " + i);
}
As the name suggests, incrementing and decrementing also works as part of an expression.
Although its use in this way may not be recommended, it's good to be aware of how the change works.
=========================================
The idea is that if the increment or decrement is after the variable,
- the value is FIRST READ into the expression
- and THEN CHANGED.
So the statement
int b = a++;
means that b INITIALLY GETS the CURRENT VALUE of a.
THEN the value of 'a' is INCREASED by one.
For example,
// from above
int a = 5;
int b = a++;
System.out.println("The value of a is " + a + " and b is " + b);
// explained later below
a = 5;
b = ++a;
System.out.println("The value of a is " + a + " amd b is " + b);
The program prints:
The value of a is 6 and b is 5 => a++ so 'a' increased from 5 to 6. BUT 'b' RETAINS INITIAL 'a' value of 5
The value of a is 6 and b is 6 => ++a so 'a' increased from 5 to 6. THEN 'b' GETS NEW 'a' value of 6
=========================================
If the VALUE CHANGE is in front of the variable,
it is performed BEFORE the EXPRESSION is EVALUATED.
So the expression
int b = ++a;
...means that the value of '
- a' is first increased by one and
- then b gets the changed value.
For example,
a = 5;
b = a--;
System.out.println("The value of a is " + a + " and b is " + b);
a = 5;
b = --a;
System.out.println("The value of a is " + a + " and b is " + b);
The program prints:
The value of a is 4 and b is 5 => a-- so 'a' decreases from 5 to 4. BUT 'b' keeps initial 'a' which is 5
The value of a is 4 and b is 4 => --a so 'a' decreases from 5 to 4. THEN 'b' gets new 'a' which is 4