String is supposed to be a bad question in an interview, but for some reason it is always asked by interviewers. Let’s take a closer look at String, starting with some of the most common interview questions.

What’s the difference between String, StringBuiler, and StringBuffer?

This question is mainly intended to ask your understanding of the three categories.

  1. The String class is immutable, while the StringBuiler and StringBuffer classes are mutable;
  2. StringBuiler is thread unsafe, StringBuffer is thread safe.

At this point, you’ve dug some holes for yourself, and once you’ve filled those holes, you’ve got the pace of the interview in your hands.

Why is the String class immutable?

public final class String
    implements java.io.Serializable.Comparable<String>, CharSequence {
    /** The value is used for character storage. */
    private final charvalue[]; . }Copy the code
  1. The String class is final, which means that String cannot be inherited, and its member methods are final by default.
  2. The array used to hold the values is also decorated with private final, indicating that it is also immutable.

For these two reasons, once a String is created it must be immutable.

So why does the following string s change?

    public static void main(String[] args) {
        String s = "abc";
        s += "12345";

        System.out.println(s); // abc12345
    }
Copy the code

Decompile the above code using the javap command:

  public static void main(java.lang.String[]);
    Code:
       0: ldc           #2                  // String abc
       2: astore_1
       3: new           #3                  // class java/lang/StringBuilder
       6: dup
       7: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
      10: aload_1
      11: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;) Ljava/lang/StringBuilder;
      14: ldc           #6                  // String 12345
      16: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;) Ljava/lang/StringBuilder;
      19: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      22: astore_1
      23: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      26: aload_1
      27: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;) V
      30: return
Copy the code

The bottom line for + concatenation is using StringBuiler, initializing a StringBuilder object, using append() concatenation, and toString() to get the result. Equivalent to the following code:

    public static void main(String[] args) {
        String s = "abc";
        StringBuilder sb = new StringBuilder();
        sb.append(s);
        sb.append("12345");
        s = sb.toString();
        System.out.println(s);
    }
Copy the code

If you look at the StringBuilder.toString() method, you’ll see that a new String is created, so it’s a new reference to s, not that s itself has changed.

So what’s the point of designing the String class to be immutable?

Security: String is used as an argument in many Java classes, such as URI, reflection, file, etc., which requires String immutable to ensure multi-threaded security without having to write complex code to do so.

How does the JVM optimize for frequent string creation?

String objects consume a lot of resources, so in order to improve performance and reduce memory overhead, the JVM proposes to use string constant pools for optimization. When creating a String, determine whether the String is in the pool of String constants. If it is, return a reference to the pool.

From this we can see that the following result is true:

public static void main(String[] args) {
    String s1 = "abc";
    String s2 = "abc";

    System.out.println(s1 == s2); // true
}
Copy the code

How many instances does the following code create?

String s1 = new String("abc");
String s2 = "abc";
String s3 = new String("abc");
Copy the code

The answer is three, which can be viewed through JVisualVM

The new String() method creates one or two, and the String method creates zero. The first line creates two objects, a String in the heap and a String constant pool. The second line finds an instance of the string object “ABC” in the constant pool and returns it directly. In the third line, we create another String in the heap.

How is StringBuffer thread safe?

The synchronized keyword is added to the StringBuffer methods. We’ll talk more about synchronized.

conclusion

String is one of the most commonly used classes in everyday development, and designers are more careful. So learn these basic classes, you can also gain, which is why the interviewer is happy to. There are many other things that can be said about strings, such as null pointer exceptions. In everyday projects, many null pointer exceptions are derived from String operations, so some development specifications also force StringUtils utility classes to operate.

Ask questions

What else do you think String can be optimized for?

Growth lies in the accumulation bit by bit, and I am on the way. Welcome to follow and like.