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

后端 未结 7 1523
暖寄归人
暖寄归人 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条回答
  •  萌比男神i
    2020-12-03 22:21

    It's also worthwhile to note that since strings are immutable, that if they are passed into a method, they can't be modified inside of the method and then have those changes seen outside of the method scope.

    public void changeIt(String s) {
        // I can't do anything to s here that changes the value 
        // original string object passed into this method
    } 
    
    public void changeIt(SomeObject o) {
        // if SomeObject is mutable, I can do things to it that will 
        // be visible outside of this method call
    } 
    

提交回复
热议问题