JavaString为什么是final/不可变的?

Why String is immutable or final in Java

Why String is immutable in java is one of the popular interviewquestion. String is one of the most used classes in any programming language.We know that String is immutable and final in java and java runtime maintains aString pool that makes it a special class.

Why String is immutable in Java?

 

why string is immutable in java, why string is immutable and final injava

Let’s look at some benefits of String immutability, that will help inunderstanding why String is immutable in java.

 

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

    2.If String is not immutablethen it would cause severe security threat to the application. For example,database username, password are passed as String to get database connection andin socket programming host and port details passed as String. Since String isimmutable it’s value can’t be changed otherwise any hacker could change the referencedvalue 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 acrossdifferent threads. This avoid the usage of synchronization for thread safety,Strings are implicitly thread safe.

    4.Strings are used in javaclassloader and immutability provides security that correct class is gettingloaded by Classloader. For example, think of an instance where you are tryingto load java.sql.Connection class but the referenced value is changed tomyhacked.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 becalculated again. This makes it a great candidate for key in a Map and it’sprocessing is fast than other HashMap key objects. This is why String is mostlyused Object as HashMap keys.

 

    Above are some of the reasonsI could think of that shows benefits of String immutability. It’s a greatfeature of Java String class and makes it special.


from:http://www.journaldev.com/802/string-immutable-final-java  

Pankaj




你可能感兴趣的:(JavaString为什么是final/不可变的?)