您的位置:首页 > 其它

++和--操作符(Auto increment and decrement)

2016-11-21 11:26 411 查看

Auto increment and decrement

Java, like C, is full of shortcuts. Shortcuts can make code much easier to type, and either 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 result.

There are two version of each type of operators, often called the prefix and postfix versions. Pre-increment means the ++ operators appears before the variable or expression, and post-increment means the ++ operators appears after the variable or expression. Similarly, pre-decrement means the - - operator appears before appears before the variable or expression, and post-decrement means the - - operator appears after the variable and 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++ and a- -), the value is produced, then the operation is performed. As an example:

Code

//: c03:AutoInc.java
// Demonstrates the ++ and -- operators.
public class AutoInc {
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-decrment
System.out.println("i-- : " + i--); // Post-decrment
System.out.println("i : " + i);
}
} ///:~


Result

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 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). C++ with the unnecessary hard parts removed, and therefore a much simple language. As you progress in Java, you’ll see that many parts are simpler, and yet Java isn’t that much easier than C++.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: