Summary of common interview difficulties of String

Common interview questions for String ...
1. Basic characteristics of string
2. Memory allocation of string
3. Basic operation of string
4. String splicing
5. intern() method ----- only at the level of Dou clan can you enter this door
6. intern other knowledge points
Common interview questions for String

1. Basic characteristics of string

String: a string represented by a pair of ""

There are two instantiation methods:

String str1 = "abc";//Literal way String str2 = new String("ABC");//new object

String is declared as final and cannot be inherited

Spring implements the Serializable interface: it means that strings support serialization,

Spring implements the Comparable interface: it means that strings can be compared

String defines final char[] value internally in jdk8 the past to store string data; Changed to byte [] in jdk9

String represents an immutable character sequence. The abbreviation is immutable

(1) When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used for assignment

@Test public void test01(){ String s1 = "abc"; //A String created as a literal is placed in the String constant pool String s2 = "abc"; //The same string will not be stored in the character window constant pool System.out.println(s1 == s2);//At this time, the addresses of two identical strings are the same: true s1 = "ABC"; //When the string is re assigned, the assigned memory area needs to be rewritten, and the original value cannot be used for assignment System.out.println(s1 == s2); //Judge the addresses of two strings, and output: false }

(2) When connecting an existing string, you also need to reassign the memory area assignment. You cannot use the original value for assignment

@Test public void test01(){ String s1 = "abc"; //A String created as a literal is placed in the String constant pool String s2 = "abc"; //The same string will not be stored in the string constant pool s2 = s2 + "def"; System.out.println(s1); System.out.println(s2); }

(3) when calling the replace() method of String to modify the specified character or String, you also need to reassign the memory area assignment

@Test public void test02(){ String s1 = "abc"; String s2 = s1.replace("a","m"); System.out.println(s1); System.out.println(s2); }

2. By literal (String str = "sss") 😉, Different from new (String str2 = new String("sss") 😉, At this time, the string is declared in the string constant pool

String constant pool: jdk7 and later versions are in heap space. Note: string constant pool will not store strings with the same content

StringPool (String constant pool): it is a HashTable with a fixed size. The default size length of jdk6 is 1009, 60013 after jdk7, and 1009 after jdk8 is the minimum value set. If too many strings are put into StringPool, Hash conflicts will be serious, resulting in a long chain list. The impact of a long chain list is to call String. Inter() The performance will be greatly reduced

Use * * - XX:StringTableSize * * to set the length of a StringTable

2. Memory allocation of string

  • There are 8 basic data types and a special type String in the Java language. In order to make them run faster and save more space, these types provide the concept of constant pool
  • Constant pools are similar to the cache provided at the Java system level. In 8, constant pools of basic data types are system coordinated, while constant pools of String type are special. There are two main ways:
    • String objects declared directly in double quotation marks will be directly stored in the constant pool. For example: String info = "abc";
    • If it is not a String object declared in double quotation marks, you can use the intern() method provided by String

String memory allocation evolution process:

1. In jdk6 and previous versions, the string constant pool is stored in the permanent generation;

2. In JDK7, the string constant pool is rectified: the position of the string constant pool is placed in the Java heap

All strings are stored in the heap, just like other ordinary objects, so that you can just adjust the size of the heap when tuning the application;

The concept of string constant pool was originally used a lot. You can use String.intern();

3. The permanent generation is eliminated in jdk8, and the meta space is introduced. The string constant pool is still saved in the Java heap

3. Basic operation of string

Basic operation code 1:

public class StringTest { public static void main(String[] args) { System.out.println();//2293 System.out.println("1");//2294 System.out.println("2"); System.out.println("3"); System.out.println("4"); System.out.println("5"); System.out.println("6"); System.out.println("7"); System.out.println("8"); System.out.println("9"); System.out.println("10");//2303 //The following strings "1" to "10" will not be loaded again System.out.println("1");//2304 System.out.println("2");//2304 System.out.println("3"); System.out.println("4"); System.out.println("5"); System.out.println("6"); System.out.println("7"); System.out.println("8"); System.out.println("9"); System.out.println("10");//2304 } }

Basic operation code 2:

class Memory { public static void main(String[] args) {//line 1 int i = 1;//line 2 Object obj = new Object();//line 3 Memory mem = new Memory();//line 4 mem.foo(obj);//line 5 }//line 9 private void foo(Object param) {//line 6 String str = param.toString();//line 7 System.out.println(str); }//line 8 }

The corresponding memory structure diagram is as follows:

4. String splicing

Note the following points:

1. The splicing results of string constants and string constants are in the string constant pool. The principle is compiler optimization;

2. Constants with the same content will not be stored in the constant pool

3. As long as one is a variable, the result will be saved in the heap. The principle of variable splicing is StringBuilder;

4. If the result of splicing calls the intern() method, the string object not yet in the constant pool will be actively put into the string constant pool, and the address of the secondary object will be returned;

Code 1 - Dumper:

@Test public void test1(){ String s1 = "a" + "b" + "c";//Compile time optimization: equivalent to "abc" String s2 = "abc"; //"abc" must be placed in the string constant pool and assigned this address to s2 /* * Finally. java is compiled into. class, and then. class is executed * String s1 = "abc"; * String s2 = "abc" */ System.out.println(s1 == s2); //True (compare both values and address values) System.out.println(s1.equals(s2)); //True (compare values only) }

Code 2 - DouWang strong

@Test public void test2(){ String s1 = "javaEE"; String s2 = "hadoop"; String s3 = "javaEEhadoop"; String s4 = "javaEE" + "hadoop";//Compile time optimization //If variables appear before and after the splicing symbol, it is equivalent to new String() in the heap space. The specific content is the splicing result: javaEEhadoop String s5 = s1 + "hadoop"; String s6 = "javaEE" + s2; String s7 = s1 + s2; System.out.println(s3 == s4);//true System.out.println(s3 == s5);//false System.out.println(s3 == s6);//false System.out.println(s3 == s7);//false System.out.println(s5 == s6);//false System.out.println(s5 == s7);//false System.out.println(s6 == s7);//false //intern(): judge whether there is a javaEEhadoop value in the string constant pool. If so, return the address of javaEEhadoop in the constant pool; //If javaEEhadoop does not exist in the string constant pool, load a copy of javaEEhadoop in the constant pool and return the address of the secondary object. String s8 = s6.intern(); System.out.println(s3 == s8);//true }

The memory structure diagram is as follows:

Analysis of the underlying principle of string splicing: douhuang peak

@Test public void test3(){ String s1 = "a"; String s2 = "b"; String s3 = "ab";//String constant pool /* The following execution details of s4 = s1 + s2: (variable s is temporarily defined based on the underlying) ① StringBuilder s = new StringBuilder(); ② s.append("a"); ③ s.append("b"); ④ s.toString(); --> Approximately equal to new String("ab"): the bottom layer calls new String("ab"), but does not store the new String object in the String (described in detail later) Supplement: StringBuilder is used after jdk5.0, and StringBuffer is used before jdk5.0 */ String s4 = s1 + s2;// System.out.println(s3 == s4);//false }

Modify the string with final - it is in the form of a constant!! (douhuang peak)

/* 1. String splicing does not necessarily use StringBuilder!!! If the left and right sides of the splice symbol are string constants or constant references, compile time optimization, that is, non StringBuilder, is still used. 2. When final is used to modify the structure of classes, methods, basic data types and reference data types, it is recommended to use it when final can be used. */ @Test public void test4(){ //At this time, modify s1 and s2 with final, and s1 and s2 are constant forms final String s1 = "a"; final String s2 = "b"; String s3 = "ab"; String s4 = s1 + s2;//At this time, instead of using StringBuilder to create objects, we get the result "ab" of s1 and s2 splicing from the constant pool System.out.println(s3 == s4);//true }

Note: the efficiency of adding strings through StringBuilder's append() api is much higher than using String string String splicing

Because String string splicing creates StringBuilder and String objects every time, which will not only waste time, but also occupy too much memory, which may lead to frequent triggering of GC

5. intern() method ----- only at the level of Dou clan can you enter this door

Use of intern() method ----- douzongyixing

If it is not a String object declared in double quotation marks, you can use the intern() method provided by String:

The intern() method will query whether the current string exists from the string constant pool?

(1) if it does not exist, the current string will be put into the string constant pool, and the returned result is the address of the string corresponding to the string constant pool

For example: String myInfo = new String("abc"). intern();

(2) if it exists, it directly returns the address of the string corresponding to the string constant pool

In other words, if the String.intern() method is called on any string, the instance to which the returned result points must be exactly the same as the string instance directly in the form of a constant, as shown in the following code:

("a" + "b" + "c").intern() = = "abc";//Return result true

Generally speaking, the intern() method is to ensure that there is only one copy of the character window in memory (string constant pool)! This can save memory space and speed up the execution of string operation tasks

* How to guarantee variables s Is it pointing to the data in the string constant pool? * There are two ways: * Mode 1: String s = "shkstart";//How literal quantities are defined * Method 2: call intern() * String s = new String("shkstart").intern(); * String s = new StringBuilder("shkstart").toString().intern();

How many objects have new String("xxx") created------ Five star peak of douzong

Answer: two objects

String s = new String("ab"); Two objects are created in heap space: One object is: new Keywords created in heap space Another object is the object in the string constant pool"ab"

How many objects will new String("xxx") + new String("yyy") create------ Douzong nine star peak

Answer: there are 5 objects. If you go deep into the bottom layer, there are 6 objects

new String("a") + new String("b")And?----5 Objects Object 1: new StringBuilder() Object 2: new String("a")----append Add to StringBuilder Object 3: in constant pool"a" Object 4: new String("b")----append Add to StringBuilder Object 5: in constant pool"b" In depth analysis: StringBuilder of toString(): Object 6: new String("ab") To emphasize, toString()The call of is not generated in the string constant pool"ab" public class StringNewTest { public static void main(String[] args) { String str = new String("a") + new String("b"); } }

Are you ready? Fight the strong

Final interview question 1 - fighting the strong

public class StringIntern { public static void main(String[] args) { String s = new String("1");//Create two objects: "1" is stored in the string constant pool s.intern();//'1' already exists in the string constant pool before calling this method String s2 = "1"; System.out.println(s == s2);//jdk6: false jdk7/8: false -------------------------------------------------------------------------------------------------------------------------------------------------- String s3 = new String("1") + new String("1");//The address of the s3 variable record is: new String("11") //After executing the previous line of code, does "11" exist in the string constant pool? Answer: does not exist!! s3.intern();//Generate "11" in the string constant pool. //jdk6: a new object "11" is created, which has a new address. //(key) jdk7/8: instead of creating "11" in the constant, an address pointing to new String("11") in the heap space is created String s4 = "11";//Address of s4 variable record: the address of "11" generated in the constant pool during the execution of the previous line of code is used System.out.println(s3 == s4);//jdk6: false jdk7/8: true } }

Note: the following version of interview questions is jdk8 (because the JDK above is too old)

Final interview question 2 - douzun peak

public class StringIntern1 { public static void main(String[] args) { //Extension of exercise in StringIntern.java: String s3 = new String("1") + new String("1");//new String("11") //After executing the previous line of code, does "11" exist in the string constant pool? Answer: does not exist!! String s4 = "11";//Generate object "11" in string constant pool String s5 = s3.intern(); System.out.println(s3 == s4);//false System.out.println(s5 == s4);//true } }

Summary: intern()

1.jdk1.6, try to put this string object into the string constant pool

If there is in the string constant pool, it will not be put into. Return the address of the object in the existing string pool;

If not, a copy of this object will be copied and put into the string constant pool, and the object address in the string constant pool will be returned;

Starting with 2.jdk1.7, try to put this string object into the string constant pool

If there is in the string pool, it will not be put in, but the address of the object with the existing string pool will be returned

If not, a copy of the reference address of the object will be copied into the string pool, and the reference address in the string pool will be returned;

intern() practice ---- fighting the saint and the strong

Exercise code 1:

public class StringExer1 { public static void main(String[] args) { String s = new String("a") + new String("b");//new String("ab") //After the execution of the previous line of code, there is no "ab" in the string constant pool String s2 = s.intern();//jdk6: create a string "ab" in the string pool //jdk8: instead of creating the string "ab" in the string pool, create a reference to the new String("ab") and return this reference System.out.println(s2 == "ab");//jdk6:true jdk8:true System.out.println(s == "ab");//jdk6:false jdk8:true } }

Memory structure diagram of jdk8 version:

Exercise code 2:

public class StringExer1 { public static void main(String[] args) { String x = "ab";//Stored in constant pool String s = new String("a") + new String("b");//new String("ab") String s2 = s.intern();//At this time, "ab" already exists in the constant pool, and its object address is directly returned to s2 System.out.println(s2 == x);//true System.out.println(s == x);//false } }

Memory structure diagram:

Exercise code 3:

public class StringExer2 { public static void main(String[] args) { String s1 = new String("a") + new String("b");After execution, it will not be generated in the string constant pool"ab" s1.intern(); String s2 = "ab"; System.out.println(s1 == s2);//true } }

Exercise code 4:

public class StringExer2 { public static void main(String[] args) { String s1 = new String("ab");//After execution, "ab" will be generated in the string constant pool s1.intern(); String s2 = "ab"; System.out.println(s1 == s2);//false } }

Summary:

At this moment, you have become the top strength of Dousheng. The interview will certainly ask the interviewer!, If you practice again, you will be able to attack the emperor

6. intern other knowledge points

Application scenario of intern()

Use intern() to test execution efficiency: space usage: for a large number of strings in the program, especially when there are many duplicate strings, using intern() can save memory space

Application scenario: a large website platform needs to store a large number of strings in memory, such as social networking sites. Many people need to store similar address information, but these addresses often have many similarities. At this time, if the strings call the intern() method, the memory size will be significantly reduced

public class StringIntern2 { static final int MAX_COUNT = 1000 * 10000; static final String[] arr = new String[MAX_COUNT]; public static void main(String[] args) { Integer[] data = new Integer[]; long start = System.currentTimeMillis(); for (int i = 0; i < MAX_COUNT; i++) { //By comparing the two methods, it can be concluded that the intern() method consumes very little memory and saves a lot of memory space //arr[i] = new String(String.valueOf(data[i % data.length])); arr[i] = new String(String.valueOf(data[i % data.length])).intern(); } long end = System.currentTimeMillis(); System.out.println("The time spent is:" + (end - start)); try { Thread.sleep(1000000); } catch (InterruptedException e) { e.printStackTrace(); } System.gc(); } }

G1 String de duplication operation of GC

Almost 25% of the data sets that survive in the Java heap are String objects, of which almost half of the String objects are duplicate (that is, string1.equals(string2) = true); The repeated String objects on the heap must be a waste of memory. Therefore, the G1 garbage collector realizes automatic and continuous de duplication of the repeated String objects, so as to avoid wasting memory

So how is it achieved?

1. When the garbage collector works, it will access the surviving objects on the heap. For each accessed object, it will check whether it is a candidate String object to be de duplicated

2. If yes, insert a reference of this object into the queue and wait for subsequent processing. A de duplication thread runs in the background to process this queue. Processing an element of the queue means deleting this element from the queue, and then try to de duplicate the String object it references

As like as two peas, 3., use hashtable to record all the non repeating char arrays used by String objects. When you want to go heavy, you will look at this hashtable to see if there is a char array in the heap.

4. If it exists, the String object will be adjusted to refer to that array, release the reference to the original array, and will eventually be recycled by the garbage collector;

5. If the search fails, the char array will be inserted into hashtable so that the array can be shared in the future;

You can use the command line to enable String de duplication:

Objects are duplicate (that is, string1.equals(string2) = true); The repeated String objects on the heap must be a waste of memory. Therefore, the G1 garbage collector realizes automatic and continuous de duplication of the repeated String objects, so as to avoid wasting memory

So how is it achieved?

1. When the garbage collector works, it will access the surviving objects on the heap. For each accessed object, it will check whether it is a candidate String object to be de duplicated

2. If yes, insert a reference of this object into the queue and wait for subsequent processing. A de duplication thread runs in the background to process this queue. Processing an element of the queue means deleting this element from the queue, and then try to de duplicate the String object it references

As like as two peas, 3., use hashtable to record all the non repeating char arrays used by String objects. When you want to go heavy, you will look at this hashtable to see if there is a char array in the heap.

4. If it exists, the String object will be adjusted to refer to that array, release the reference to the original array, and will eventually be recycled by the garbage collector;

5. If the search fails, the char array will be inserted into hashtable so that the array can be shared in the future;

You can use the command line to enable String de duplication:

UseStringDeduplication(bool)

9 October 2021, 08:02 | Views: 1460

Add new comment

For adding a comment, please log in
or create account

0 comments