简体   繁体   English

您可以在Java中与增量运算符一起使用哪种操作数?

[英]What kind of operands can you use with the increment operator in Java?

I don't know what happens if I apply the increment operator on an expression in 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++;

Can you increment an element of an array the way the first example is showing? 您可以按照第一个示例所示的方式递增数组的元素吗?

Can you increment a field in a class (I do know about encapsulation and getters/setters, my question is syntax-semantics oriented) the way I show in the second example? 您是否可以按照第二个示例中的方式增加类中的字段(我确实知道封装和getters / setters,我的问题是面向语法语义的)?

I remember the age of C/C++. 我记得C / C ++的时代。 There used to be a problem with p -> x++, for example. 例如,p-> x ++曾经存在问题。 You sometimes needed to enclose complex expressions in parentheses when using increment or decrement. 使用增量或减量时,有时需要将复杂的表达式括在括号中。

Thank you for any hints. 谢谢您的提示。

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. p.myCar.yearMadeai[0]都是变量(分别是实例变量和局部变量) ,因此可以用作这四个运算符中任何一个的操作数。

4.12. 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). 变量是存储位置,并且具有关联的类型,有时称为其编译时类型,它是原始类型(第4.2节)或引用类型(第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.26)或前缀或后缀++(递增)或-(递减)运算符(§15.14.2,§15.14.3,§15.15.1,§15.15.2)进行更改)。

... ...

15.14.2. 15.14.2。 Postfix Increment Operator ++ Postfix增量运算符++

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. 否则,将值1加到变量的值上,然后将总和存储回变量中。 Before the addition, binary numeric promotion (§5.6.2) is performed on the value 1 and the value of the variable. 在添加之前,对值1和变量的值执行二进制数值提升(第5.6.2节)。 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. 如有必要,可通过缩小原始转换(第5.1.3节)来对和进行缩小,和/或在存储变量之前,先对变量的类型进行装箱转换(第5.1.7节)。 The value of the postfix increment expression is the value of the variable before the new value is stored. 后缀增量表达式的值是存储新值之前的变量值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM