Why new keyword not needed for String

后端 未结 4 719
耶瑟儿~
耶瑟儿~ 2020-12-07 19:18

I am new in java.

In java, String is a class.But we do not have to use new keyword to create an object of class String<

4条回答
  •  自闭症患者
    2020-12-07 19:43

    The Java language specification allows for representation of a string as a literal. You can consider it a shortcut initialization for a String that has one important side-effect that is different from regular initialization via new

    String literals are all interned, which means that they are constant values stored by the Java runtime and can be shared across multiple classes. For example:

    class MainClass (
        public String test = "hello";
    }
    
    class OtherClass {
       public String another = "hello";
    
       public OtherClass() {
           MainClass main = new MainClass();
           System.out.println(main.test == another);
       }
    }
    

    Would print out "true" since, both String instances actually point to the same object. This would not be the case if you initialize the strings via the new keyword.

提交回复
热议问题