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


ps。这不是功课。我是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);
    }


为什么在第二段代码中更新而不在第一段代码中更新?

最佳答案

这确实与传递值无关†

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中的“传递原始数据类型参数”部分

关于java - 为什么每次乘法后我的变量的值都没有更新?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31616543/

10-09 02:27