String consolidation

About String in Java

                如今做了一个重大决定,不定期温习The Basement Of Java
  1. Cognitive brief of String object
    First of all, String does not belong to the 8 basic data types, String is an object. Because the default value of an object is null. But it is also a special kind of object, with some properties that its object does not have.
    Both new String() and new String("") declare an empty string, not null.
  2. Constant pool (constant pool)
    The constant pool refers to some data that is determined at compile time and saved in the compiled .class file. It includes constants about classes, methods, interfaces, etc., as well as string constants.
  3. String pool
    There is a string pool in the JVM, which holds many String objects and can be shared, so it improves efficiency. The String class is final, and its value cannot be changed once it is created, so we don't have to worry about the program confusion caused by String sharing. String pool is maintained by String class, we can call intern() method to access the string pool.
  • Example 1
    public class Test {
    public static void main(String args[]) {
    String str0 = "abc";
    String str1 = "abc";
    String str2 = "a" + "bc";
    System.out.println(str0 = = str1);
    System.out.println(str0 == str2);
    }
    }
    Running result:
    true
    true
    Explanation: Java will ensure that a string constant is only copied, because str0 in the example and "abc" in "str1" They are all string constants, they are determined at compile time, so str0==str1 is true; and "a" and "" and bc" are also characters, when a character is formed by concatenating multiple strings It must be a string constant itself, so s2 is also parsed as a string constant at compile time. So it follows that
    str0 = str1 = str2
  • Example 2
    public class Test {
    public static void main(String args[]) {
    String str0 = "kvill";
    String str1 = new String("kvill");
    String str2 = "k" + new String("ill");
    System.out.println(str0 == str1);
    System.out.println(str0 == str2);
    System.out.println(str1 == str2);
    }
    }
    Running result:
    false
    false
    false
    In example 2, str0 is still constant For the application of "kvill" in the pool, str1 cannot be determined at compile time, so it is a reference to the new object "kvill" created at runtime, and str2 cannot be determined at compile time because it has the second half of new String("ill"). , so is also an application of a newly created object "kvill".
    Now that I understand this, I understand why this result is obtained.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325476207&siteId=291194637