Auto increment and decrement
Java, like C, is full of shortcuts. Shortcuts can make code much easier to type, and either easier or harder to read.
Two of the nicer shortcuts are the increment and decrement operators (often referred to as the auto-increment and auto-decrement operators). The decrement operator is -- and means “decrease by one unit.” The increment operator is ++ and means “increase by one unit.” If a is an int, for example, the expression ++a is equivalent to (a = a + 1). Increment and decrement operators not only modify the variable, but also produce the value of the variable as a result.
There are two versions of each type of operator, often called the prefix and postfix versions. Pre-increment means the ++ operator appears before the variable or expression, and post-increment means the ++ operator appears after the variable or expression. Similarly, pre-decrement means the -- operator appears before the variable or expression, and post-decrement means the -- operator appears after the variable or expression. For pre-increment and pre-decrement, (i.e., ++a or --a), the operation is performed and the value is produced. For post-increment and post-decrement (i.e. a++ or a--), the value is produced, then the operation is performed. As an example:
//: c03:AutoInc.java
// Demonstrates the ++ and -- operators.
import com.bruceeckel.simpletest.*;
public class AutoInc {
static Test monitor = new Test();
public static void main(String[] args) {
int i = 1;
System.out.println("i : " + i);
System.out.println("++i : " + ++i); // Pre-increment
System.out.println("i++ : " + i++); // Post-increment
System.out.println("i : " + i);
System.out.println("--i : " + --i); // Pre-decrement
System.out.println("i-- : " + i--); // Post-decrement
System.out.println("i : " + i);
monitor.expect(new String[] {
"i : 1",
"++i : 2",
"i++ : 2",
"i : 3",
"--i : 2",
"i-- : 2",
"i : 1"
});
}
} ///:~
You can see that for the prefix form, you get the value after the operation has been performed, but with the postfix form, you get the value before the operation is performed. These are the only operators (other than those involving assignment) that have side effects. (That is, they change the operand rather than using just its value.)
The increment operator is one explanation for the name C++, implying “one step beyond C.” In an early Java speech, Bill Joy (one of the Java creators), said that “Java=C++--” (C plus plus minus minus), suggesting that Java is C++ with the unnecessary hard parts removed, and therefore a much simpler language. As you progress in this book, you’ll see that many parts are simpler, and yet Java isn’t that much easier than C++.