Why String objects are immutable?

  1. String pool was possible because strings in Java are immutable. Java Runtime Environment thus saving a lot of stack space, because the same variable String String variable can refer to different pools. String If not immutable, the string resides ( String interning ) would not be possible, because once a variable changes value String object referenced by any one, which will be reflected in the other variables.
  2. If the string is not immutable, it might cause serious application security threats. For example, the database user name and password are passed as a String to get the database connection, the Socket programming host and port information as well. Since the strings are immutable, so its value can not be changed. Otherwise, any hacker can tamper with its reference value, which can lead to security problems in the application.
  3. Since String is immutable, and thus it multithreading it is safe for, and may share a single String instance between different threads. This avoids the use of synchronous thread-safe; the string is implicit thread-safe.
  4. String is used in the Java class loader, which is immutable class loader to load the correct class provides security. Otherwise, consider such a dangerous situation, you try to load the  java.sql.Connection class, you reference value was changed to  myhacked.Connection, and you do not need it to perform operations on the database.
  5. Since String is immutable, so when it was created it was cached hash code, need not be calculated again. This makes it an ideal target key mapping, its processing faster than other HashMap fast key types. That's why String is  HashMap the most common type of bond.

Guess you like

Origin blog.csdn.net/xingqibaing/article/details/86526143