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

本文介绍了Java中增减运算符的基本用法及其两种形式:前缀和后缀。通过示例代码展示了这两种形式的区别,并解释了它们如何改变变量值并返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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++.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值