String can't change. But int, char can change

后端 未结 7 1531
暖寄归人
暖寄归人 2020-12-03 21:24

I\'ve read that in Java an object of type String can\'t change. But int and char variables can. Why is it? Can you give me an example?

Thank you. (I am a newer -_- )

7条回答
  •  半阙折子戏
    2020-12-03 21:59

    String is an immutable type (the value inside of it cannot change). The same is true for all primitive types (boolean, byte, char, short, int, long, float, and double).

    int    x;
    String s;
    
    x = 1;
    x = 2;
    s = "hello";
    s = "world";
    x++; // x = x + 1;
    x--; // x = x - 1;
    

    As you can see, in no case can you alter the constant value (1, 2, "hello", "world") but you can alter where they are pointing (if you warp your mind a bit and say that an int variable points at a constant int value).

提交回复
热议问题