Why String Class is Immutable or Final in Java ?

Since String objects are cached in a String pool, it makes sense to make the String immutable. The cached String literals are shared between multiple clients. And there is a possibility that one client's action may affect another client’s access to String pool.

String is also used as a parameter in many Java classes. Eg. You can pass hostname, port number as String while opening a network connection. If any one can modify your copy of the String, it can change the hostname. Due to this reason, it makes sense to make String final as soon as it is created.



You May Interest

What are the Differences Between a Vector and an ArrayList in Jav ...

What are the Differences Between a Checked and Unchecked Exceptio ...

Why Do You Use Upcasting or Downcasting in Java ?

What is the Difference Between sendRedirect and forward in a JSP ...

What are the Thread-safe Classes in Java Collections Framework ?