Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

because the real question is “Why must Strings be immutable?

immutable strings
0
Posted

because the real question is “Why must Strings be immutable?

0

One reason is efficiency. It’s easier to optimize accesses to an object that is known to be immutable. Strings are very commonly used, even used behind the scenes by the Java compiler. Efficiency gains in the String class can yield big dividends. If no one can change a String, then you never have to worry about who else has a reference to your String. A more compelling reason is security. Before String was changed to be final (while Java 1.0 was still in beta) there was a race condition which could be used to subvert security restrictions. It had to do with having one thread change a pathname while another thread was about to open it. There are other ways to solve these problems, but making String final is the one that the designers chose.

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123