首页 > 解决方案 > Java 中的自增运算符可以使用哪些类型的操作数?

问题描述

我不知道如果我将增量​​运算符应用于 Java 中的表达式会发生什么。

int ai[] = new ai[10];
ai[0]++;

// ***

class Car {
  public int yearMade = 0;
}

class Person {
  public Car myCar = new Car();
}

Person p = new Person();
p.myCar.yearMade++;

您可以按照第一个示例显示的方式增加数组的元素吗?

你能像我在第二个例子中展示的那样增加一个类中的一个字段(我知道封装和getter/setter,我的问题是面向语法语义的)吗?

我记得 C/C++ 的时代。例如,以前 p -> x++ 存在问题。使用增量或减量时,有时需要将复杂的表达式括在括号中。

谢谢你的任何提示。

标签: javaoperatorsjlsoperands

解决方案


The answer to both your questions is "Yes, you can". Both p.myCar.yearMade and ai[0] are variables (an instance variable and a local variable, respectively), and, thus, can be used as operands for any of these four operators.

4.12. Variables

A variable is a storage location and has an associated type, sometimes called its compile-time type, that is either a primitive type (§4.2) or a reference type (§4.3).

A variable's value is changed by an assignment (§15.26) or by a prefix or postfix ++ (increment) or -- (decrement) operator (§15.14.2, §15.14.3, §15.15.1, §15.15.2).

...

15.14.2. Postfix Increment Operator ++

At run time, if evaluation of the operand expression completes abruptly, then the postfix increment expression completes abruptly for the same reason and no incrementation occurs. Otherwise, the value 1 is added to the value of the variable and the sum is stored back into the variable. Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. If necessary, the sum is narrowed by a narrowing primitive conversion (§5.1.3) and/or subjected to boxing conversion (§5.1.7) to the type of the variable before it is stored. The value of the postfix increment expression is the value of the variable before the new value is stored.


推荐阅读