为什么在poc
内完成每次乘法后,我的变量System.out.println();
的值没有更新?
public static void main(String[] args) {
byte poc = 0b0001;
System.out.println("The value of byte " + poc + " when multiplied by 0010 is: " + poc*0b0010);
System.out.println("The value of byte " + poc + " when multiplied by 0010 is: " + poc*0b0010);
System.out.println("The value of byte " + poc + " when multiplied by 0010 is: " + poc*0b0010);
System.out.println("The value of byte " + poc + " when multiplied by 0010 is: " + poc*0b0010);
System.out.println("The value of byte " + poc + " when multiplied by 0010 is: " + poc*0b0010);
System.out.println("The value of byte " + poc + " when multiplied by 0010 is: " + poc*0b0010);
System.out.println("The value of byte " + poc + " when multiplied by 0010 is: " + poc*0b0010);
System.out.println("The value of byte " + poc + " when multiplied by 0010 is: " + poc*0b0010);
}
P.S。这不是功课。我是Java的新手,我正在努力掌握传值的概念。我不明白为什么poc
每次在println
语句中加倍时都不会更新poc
的值。例如,在以下代码中,变量public static void main(String[] args) {
byte poc = 0b0001;
System.out.println("The value of byte " + poc + " when incremented by 1 is: " + ++poc);
System.out.println("The value of byte " + poc + " when incremented by 1 is: " + ++poc);
System.out.println("The value of byte " + poc + " when incremented by 1 is: " + ++poc);
System.out.println("The value of byte " + poc + " when incremented by 1 is: " + ++poc);
System.out.println("The value of byte " + poc + " when incremented by 1 is: " + ++poc);
System.out.println("The value of byte " + poc + " when incremented by 1 is: " + ++poc);
System.out.println("The value of byte " + poc + " when incremented by 1 is: " + ++poc);
System.out.println("The value of byte " + poc + " when incremented by 1 is: " + ++poc);
}
每次都会更新。
MethodArgumentNotValidException
为什么在第二段代码中更新,但在第一段代码中没有更新?
答案 0 :(得分:5)
这与传递值†
无关 poc*0b0010
不是将poc*0b0010
的结果赋给poc
的语句,它只是一个返回乘法结果的表达式。
++poc
是一个表达式,它增加poc
(赋值)并返回赋值的结果。
请注意,您可以使用*=
(a compound assignment operator)执行此操作,方法是将poc*0b0010
括在括号中,在字符串连接中创建Parenthesized Expression:
System.out.println("The value of byte " + poc
+ " when multiplied by 0010 is: " + (poc*=0b0010));
有关算术和作业的完整教程,请参阅The Java Tutorials > Assignment, Arithmetic, and Unary Operators。
另见JLS: 15.15.1. Prefix Increment Operator ++和15.17.1. Multiplication Operator *
† 有关按值传递的信息,请参阅"传递原始数据类型参数"在this java tutorial
答案 1 :(得分:1)
发生这种情况的原因是poc*0b0010
仅返回一个值,而++poc
增加poc
的值,然后返回更新后的poc
值。< / p>
基本上++poc
是poc = poc + 1;
的简写,请注意poc + 1
的结果是如何分配给poc的。
然而,poc*0b0010
只是算术执行&amp;返回,但没有分配给任何东西。
如果您使用poc *= 0b0010
,那么表达式将等同于poc = poc * 0b0010
。
最后一点说明:这种行为实际上与传值和传递引用无关,而是与赋值和算术与一元运算之间的区别有关。