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

后端 未结 7 1515
暖寄归人
暖寄归人 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 22:05

    I'm not sure that it is possible to show (by example) that Strings cannot change. But you can confirm this by reading the description section of Javadoc for the String class, then reading the methods section and noting that there are no methods that can change a String.

    EDIT: There are many reasons why Strings are designed to be immutable in Java. The most important reason is that immutable Strings are easier to use correctly than mutable ones. And if you do need the mutable equivalent of a String for some reason, you can use the StringBuilder (or StringBuffer) class.

提交回复
热议问题