Are Java primitives immutable?

前端 未结 6 1924
野的像风
野的像风 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:09

    Immutable means that each time the value of and object has changed a new reference is created for it on stack. You can't talk about immutability in case of primitive types,only the Wrapper Classes are immutable. Java uses copy_by_value not by reference.

    It makes no difference if you're passing primitive or reference variables, you are always passing a copy of the bits in the variable. So for a primitive variable, you're passing a copy of the bits representing the value and if you're passing an object reference variable, you're passing a copy of the bits representing the reference to an object.

    For example, if you pass an int variable with the value of 3, you're passing a copy of the bits representing 3.

    Once a primitive has been declared, its primitive type can never change, although its value can change.

提交回复
热议问题