Are Java primitives immutable?

前端 未结 6 1935
野的像风
野的像风 2020-12-04 23:55

If a method has a local variable i:

int i = 10;

and then I assign a new value:

i = 11;

Will

6条回答
  •  生来不讨喜
    2020-12-05 00:18

    This isn't a full answer, but it is a way to prove the immutability of primitive-type values.

    If primitive values (literals) are mutable, then the following code would work fine:

    int i = 10; // assigned i the literal value of 10
    5 = i; // reassign the value of 5 to equal 10
    System.out.println(5); // prints 10
    

    Of course, this isn't true.

    The integer values, such as 5, 10 and 11 are already stored in the memory. When you set a variable equal to one of them: it changes the value in the memory-slot where i is.

    You can see this here through the bytecode for the following code:

    public void test(){
        int i = 10;
        i = 11;
        i = 10;
    }
    

    Bytecode:

    // access flags 0x1
    public test()V
     L0
      LINENUMBER 26 L0
      BIPUSH 10 // retrieve literal value 10
      ISTORE 1  // store it in value at stack 1: i
     L1
      LINENUMBER 27 L1
      BIPUSH 11 // same, but for literal value 11
      ISTORE 1
     L2
      LINENUMBER 28 L2
      BIPUSH 10 // repeat of first set. Still references the same literal 10. 
      ISTORE 1 
     L3
      LINENUMBER 29 L3
      RETURN
     L4
      LOCALVARIABLE this LTest; L0 L4 0
      LOCALVARIABLE i I L1 L4 1
      MAXSTACK = 1
      MAXLOCALS = 2
    

    As you can see in the bytecode (hopefully) it references the literal value (example: 10) and then stores it in the slot for variable i. When you change the value of i, you are just changing which value is stored in that slot. The values themselves aren't changing, the location of them is.

提交回复
热议问题