我们可以使用显式或隐式结构创建字符串.
隐含的构造示例:
String str1 = "hello";
String str2 = "hello";
str1==str2 // returns true, both str1 and str2 points to the same String object in string pool
Run Code Online (Sandbox Code Playgroud)
明确的构造示例
String str3 = new String("hello");
String str4 = new String("hello")
str3==str4 // returns false because str3 and str4 points to different String object
Run Code Online (Sandbox Code Playgroud)
因为使用隐式构造首选(内存保存)为什么我们不应该使用==运算符?据我所知,不使用==运算符的唯一原因是我们可以忘记不使用显式结构并尝试做类似的事情
str1==str3
str3==str4 // and so forth
Run Code Online (Sandbox Code Playgroud)
来自您的代码的文字字符串被实习.这就是为什么它们在你的例子中是同一个对象的原因.
但是,程序中并非所有字符串都来自您的代码,有些来自各种输入(例如用户输入或文件),或来自您构建它们的操作,并且这些字符串不会被实现(除非您要求它).这些字符串通常都不是==偶然的equal.