Some questions about String, StringBuilder, StringBuffer in Java

1. Can the String class be inherited?

The String class is modified with the final keyword when it is declared, and the class modified by the final keyword cannot be inherited.

Next we can look at the source code snippet of the String class:

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

    /** use serialVersionUID from JDK 1.0.2 for interoperability */
    private static final long serialVersionUID = -6849794470754667710L;

** Why did the developers of the Java language define the String class as final? **

Because the string pool is only possible if the string is immutable. The implementation of string pool can save a lot of heap space at runtime, because different string variables all point to the same string in the pool. But if the string is variable, then String interning will not be implemented, because in this case, if the variable changes its value, then the value of other variables pointing to this value will also change. If the string is variable, it will cause serious security problems. For example, the user name and password of the database are passed in in the form of strings to obtain the database connection, or in socket programming, the host name and port are passed in as strings. Because the string is immutable, its value is immutable, otherwise hackers can get into the loop and change the value of the object pointed to by the string, causing security holes.

Because strings are immutable, they are multi-thread safe, and the same string instance can be shared by multiple threads. This eliminates the need to use synchronization because of thread safety issues. The string itself is thread-safe.

Because the string is immutable, the HashCode is cached when it is created and does not need to be recalculated. This makes the string very suitable as a key in the Map, and the processing speed of the string is faster than other key objects. This is that the keys in HashMap often use strings.

In addition to modifying the class, what other uses of the final keyword are there?

The final modified variable cannot be reassigned once it is assigned;

The final modified method cannot be overwritten;

Final modified instance variables must be manually assigned, and the system default values ​​cannot be used;

Final modified instance variables are generally used in conjunction with static to declare constants;

Note: final cannot be combined with abstract keyword.

In short, final means final and immutable.

4. What is the difference between String, StringBuilder and StringBuffer?

The Java platform provides two types of strings: String and StringBuffer/StringBuilder, both of which can store and manipulate strings. The differences are as follows:

● String is a read-only string, which means that the content of the string referenced by String cannot be changed. Beginners may have this misunderstanding:

String str = “abc”;

str = “bcd”;

As above, the string str can obviously be changed! Actually, str is just a reference object, which points to a string object "abc". The meaning of the second line of code is to make str re-point to a new string "bcd" object, and the "abc" object has not changed, but the object "abc" has no reference to it.

● The string object represented by StringBuffer/StringBuilder can be modified directly.

● StringBuilder was introduced in Java5, and its methods are exactly the same as StringBuffer. The difference is that it is used in a single-threaded environment, because all its methods are not modified by synchronized, so its efficiency is theoretically higher than StringBuffer. .

● Variable and immutable

String: String constant, which will not change itself when modified; if modified, it is equivalent to regenerating a new string object.

StringBuffer: The object itself will be changed when it is modified. Each operation is to modify the StringBuffer object itself, not to generate a new object; usage scenarios: when the string is frequently changed, the main methods: append(), insert(), etc. .

● Is the thread safe

String: After the object is defined, it is immutable and thread-safe.

StringBuffer: It is thread-safe (a synchronization lock is added to the calling method), the execution efficiency is slow, and it is suitable for manipulating large amounts of data in the string buffer under multithreading.

StringBuilder: It is thread-unsafe and is suitable for manipulating large amounts of data in the string buffer under a single thread.

● Common Points

StringBuilder and StringBuffer have a common parent class AbstractStringBuilder (abstract class).

The methods of StringBuilder and StringBuffer will call public methods in AbstractStringBuilder, such as super.append(...). Only StringBuffer will add the synchronized keyword to the method for synchronization. Finally, if the program is not multi-threaded, then using StringBuilder is more efficient than StringBuffer.

5. Please tell the output of the following program ?

class StringEqualTest {
public static void main(String[] args) {
String s1 = “Programming”;
String s2 = new String(“Programming”);
String s3 = “Program”;
String s4 = “ming”;
String s5 = “Program” + “ming”;
String s6 = s3 + s4;
System.out.println(s1 == s2); //false
System.out.println(s1 == s5); //true
System.out.println(s1 == s6); //false
System.out.println(s1 == s6.intern()); //true
System.out.println(s2 == s2.intern()); //false
}
}

Supplement: To answer the above interview questions, you need to know the following two knowledge points:

● The intern() method of the String object will get the reference of the corresponding version of the string object in the constant pool (if there is a string in the constant pool and the equals result of the String object is true), if there is no corresponding string in the constant pool , The string will be added to the constant pool, and then a reference to the string in the constant pool will be returned;

● The essence of the string + operation is to create a StringBuilder object for append operation, and then use the toString method to process the spliced ​​StringBuilder object into a String object. You can use the javap -c StringEqualTest.class command to get the JVM word corresponding to the class file The section code instruction can be seen.

Guess you like

Origin blog.csdn.net/weixin_38019299/article/details/108084364