Why String type designed to be immutable?

This article is reproduced in the Java technology stack architect micro-channel public number

 

These days in the major platforms have seen some posts like this, all questions about the type of String objects immutable, of course, is now looking for work in the preparation period, and therefore spent part of their time to sort out.

I want to completely understand the String, where we need to address the following questions

(1) What is immutable?

How (2) String is designed to be immutable objects?

(3) there is any way to change String?

(4) JAVA language Why String type designed to be immutable?

With these questions you can start today of the article.

First, what is an immutable object

Can also be understood from the literal meaning, that is our target to create immutable. So what is it immutable? In order to achieve the object created immutable, java language requirements we need to abide by the following five rules:

Internal (1) class all the fields are final modified.

(2) internal class all fields are private, that is modified private.

(3) class can not be integrated and expanded.

(4) class method which can not be able to modify the internal state of the foreign offer, setter method does not work.

(5) inside the class field if it is referenced, which means you can point to the object variable, then we programmers can not get this reference.

It is because of our String type follows the five rules above, so just say String objects are immutable. Want to get to know him or look at five rules of type String inside look at the top looks like it.

Two, String how they are designed to be immutable objects

1, a doubt

Before looking at, let's give a doubt, we look at the code below,

public class Test2 {
    public static void main(String[] args) {
        String a="张三";
        System.out.println(a);
        a="李四";
        System.out.println(a);
    }
}

 

 

 

In the beginning of the article we said, String objects are immutable, where a = Joe Smith, then a = John Doe, in line with String immutability of thing? The answer is of course in line.

 

 

We can see from the above picture, the first time String a = "John Doe" in a heap create the same object "Joe Smith." And then later in memory when we execute a = "John Doe" and create an object of "John Doe." That's a we just changed the address of a reference point only.

2, the source explained doubt

Since a pointed reference to the address changed, then there must be a String its internal variables can point to a different actual object, we want to further clarify its String into the interior to see.

We are here mainly through the source code of the String class to analyze, look at how the Java language design, can String type designed to be immutable. Here are part jdk1.8 source.

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final char value[];

    /** Cache the hash code for the string */
    private int hash; // Default to 0
    ......
}
 

The above two main fields: value and hash. We are here mainly to see the value array, hash and off-topic will not explain it here, and I have a special article describes hash.

Our String object is actually inside a character then this value is stored in an array inside. But there is no value outside setValue method, the entire outside of the String object seems, is immutable. We draw a diagram to explain the above doubts

 

 

Now I understand it, that real change is quoted value, because value is an array reference. This can also be easily interpreted at a puzzled problem.

3, two doubts

Since our String is immutable, it seems there are many internal substring, replace, methods replaceAll these operations. It seems to change the String object, it is also very simple to explain, every time we replace these operations, in fact, create a new object in the heap memory. Then we point to the value of different objects Bale.

When the interview we just explain the reasons for the above fact is not so perfect, you want to raise to better the loading force, we need to answer further.

Third, there is any way to change String

Since there is this title. It is surely a way, do not forget our reflection mechanism, under normal circumstances, he can make some things in violation of the principles of design language. It is also a skill, every interviewer asks questions designed to violate the principles of the language, you can take reflection to refute him. Here we look at:

public  static  void main (String [] args) { 
        String STR = "John Doe" ; 
        System.out.println (STR); 
        the try {
             // we obtain the internal reflection by the value character array 
            Field, Field = String. class .getDeclaredField ( "value" ); 
            field.setAccessible ( to true );
             char [] value; 
            value = ( char []) Field.get (STR);
             // the first character becomes king 
            value [0] = 'WANG ' ; 
            System.out.println (STR); 
        } the catch (Exception e) {
            e.printStackTrace();
        }
    }

 

We can change String by reflection.

Now we know how it works and usage, but also know that you can change the String through reflection, there is a problem we do not figure out the interview you can ask him to further enhance their force grid.

Four, JAVA language why String type designed to be immutable

Here are a few features.

First: In the Java program is the most used type String, which involves a large number of additions and deletions, additions and deletions in fact, every time jvm need to check the security of the poor before the change String object is through hashcode, when not designed to becomes the object when the operation ensures the uniqueness of each of the CRUD hashcode, also can be assured.

Second: the network connection address URL, file path path usually are saved as a String type, String if not fixed, it will cause all kinds of security risks. Like our password can not be saved to the type String, that if you save the password in clear text to a string, then it will always remain in memory until the garbage collector to clear it. And because the string is placed in the buffer pool string for easy re-use, so it could be preserved for a long time in memory, and this will lead to security risks

Third: the string value is retained in the constant pool, if that is allowed to change a string object, it will lead to all kinds of logical errors

OK, the above is the reason why objects of type String immutable. When the interview can answer them just fine, if the problem also please correct me.

Guess you like

Origin www.cnblogs.com/lusaisai/p/12390080.html