现在的位置: 首页 > 综合 > 正文

Why String is immutable or final in Java

2018年05月24日 ⁄ 综合 ⁄ 共 1762字 ⁄ 字号 评论关闭

http://www.journaldev.com/802/why-string-is-immutable-or-final-in-java

String is one of the most used classes in any programming language. As we know that String is immutable and final in java and java runtime maintains a String pool that
makes it a special class.

String immutable Benefits

1. String pool is possible only because String is immutable in java, this way Java Runtime saves a lot of java heap space because different String variables can refer
to same String variable in the pool. If String would not have been immutable, then String interning would not have been possible because if any variable would have changed the value, it would have been reflected to other variables also.

2. If String is not immutable then it would cause severe security threat to the application. For example, database username, password are passed as String to get database connection and in socket
programming
 host and port details passed as String. Since String is immutable it’s value can’t be changed otherwise any hacker could change the referenced value to cause security issues in the application.

3. Since String is immutable, it is safe for multithreading and a single String instance can be shared across different threads. This avoid the usage of synchronization for thread safety, Strings are implicitly thread safe.

4. Strings are used in java classloader and immutability provides security that correct class is getting loaded by Classloader.
For example, think of an instance where you are trying to load java.sql.Connection class but the referenced value is changed to myhacked.Connection class that can do unwanted things to your database.

5. Since String is immutable, its hashcode is cached
at the time of creation and it doesn’t need to be calculated again. This makes it a great candidate for key in a Map and it’s processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

Above are some of the reasons I could think of that shows benefits of String immutability. It’s a great feature of Java String class and makes it special.

抱歉!评论已关闭.