Java basic content (3)

1. When using strings, which method is recommended for new and ""?

Let’s first look at the difference between "hello" and new String("hello"):

  • When a Java program directly uses the string literal of "hello", the JVM will use the constant pool to manage this string;

  • When using new String("hello"), the JVM will first use the constant pool to manage the "hello" direct variable, and then call the constructor of the String class to create a new String object. The newly created String object is saved in the heap memory. middle. Moreover, the data of the object in the heap will point to the direct value in the constant pool.

Obviously, using new will create one more object and occupy more memory, so it is generally recommended to use direct methods to create strings.

2. Tell me about your understanding of string concatenation

  1. + operator: If all string literals are spliced, it is suitable to use the + operator to implement splicing;

  2. StringBuilder: If the concatenated string contains variables and does not require thread safety, StringBuilder is suitable;

  3. StringBuffer: If the concatenated string contains variables and requires thread safety, StringBuffer is suitable;

  4. The concat method of the String class: If you are just concatenating two strings and contain variables, the concat method is suitable;

3. How is the bottom layer of adding two strings implemented?

If all string literals are spliced, the compiler will directly optimize it into a complete string during compilation, which is the same as if you directly write a complete string.

If the spliced ​​string contains variables, the compiler uses StringBuilder to optimize it during compilation, that is, it automatically creates a StringBuilder instance and calls its append() method to splice these strings together.

Guess you like

Origin blog.csdn.net/m0_63732435/article/details/132968719