Java Reference
In-Depth Information
6
public static void main(String[] args)
7
{
8
// demonstrate postfix increment operator
9
int c = 5 ;
10
System.out.printf( "c before postincrement: %d%n" , c); // prints 5
11
System.out.printf( " postincrementing c: %d%n" , c++); // prints 5
System.out.printf( " c after postincrement: %d%n" , c); // prints 6
12
13
14
System.out.println(); // skip a line
15
16
// demonstrate prefix increment operator
17
c = 5 ;
18
System.out.printf( " c before preincrement: %d%n" , c); // prints 5
19
System.out.printf( " preincrementing c: %d%n" , ++c); // prints 6
System.out.printf( " c after preincrement: %d%n" , c); // prints 6
20
21
}
22
} // end class Increment
c before postincrement: 5
postincrementing c: 5
c after postincrement: 6
c before preincrement: 5
preincrementing c: 6
c after preincrement: 6
Fig. 4.15 | Prefix increment and postfix increment operators. (Part 2 of 2.)
Simplifying Statements with the Arithmetic Compound Assignment, Increment and
Decrement Operators
The arithmetic compound assignment operators and the increment and decrement oper-
ators can be used to simplify program statements. For example, the three assignment state-
ments in Fig. 4.12 (lines 26, 28 and 31)
passes = passes + 1 ;
failures = failures + 1 ;
studentCounter = studentCounter + 1 ;
can be written more concisely with compound assignment operators as
passes += 1 ;
failures += 1 ;
studentCounter += 1 ;
with prefix increment operators as
++passes;
++failures;
++studentCounter;
or with postfix increment operators as
passes++;
failures++;
studentCounter++;
 
Search WWH ::




Custom Search