Java Reference
In-Depth Information
decrement
operator
Everything we said about the increment operator applies to the decrement operator
as well, except that the value of the variable is decreased by one rather than increased by
one. For example, consider the following code:
int n = 8;
int valueProduced = n−−;
System.out.println(valueProduced);
System.out.println(n);
This produces the following output:
8
7
On the other hand, the code
int n = 8;
int valueProduced = −−n;
System.out.println(valueProduced);
System.out.println(n);
produces the following output:
7
7
Both n−− and −−n change the value of n by subtracting one, but they evaluate to
different values. n−− evaluates to the value n had before it was decremented; on the
other hand, −−n evaluates to the value n has after it is decremented.
You cannot apply the increment and decrement operators to anything other than a
single variable. Expressions such as (x + y)++,−−(x + y) , 5++ , and so forth are all
illegal in Java.
The use of the increment and decrement operators can be confusing when used
inside of more complicated expressions, and so, we prefer to not use increment or
decrement operators inside of expressions, but to only use them as simple statements,
such as the following:
n++;
Self-Test Exercises
22. What is the output produced by the following lines of program code?
int n = ( int )3.9;
System.out.println("n == " + n);
 
Search WWH ::




Custom Search