为什么每次乘法后我的变量值都没有更新?

时间:2015-07-24 17:35:17

标签: java immutability

为什么在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

为什么在第二段代码中更新,但在第一段代码中没有更新?

2 个答案:

答案 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>

基本上++pocpoc = poc + 1;的简写,请注意poc + 1的结果是如何分配给poc的。

然而,poc*0b0010只是算术执行&amp;返回,但没有分配给任何东西。

如果您使用poc *= 0b0010,那么表达式将等同于poc = poc * 0b0010

最后一点说明:这种行为实际上与传值和传递引用无关,而是与赋值和算术与一元运算之间的区别有关。