2017-10-01 116 views
-2

这两个字符串声明有什么区别?java中的字符串声明

String s1 = "tis is sample"; 
String s2 = new String ("tis is sample"); 

当我检查s1==s2它说false

为什么它是false

你还可以解释这两个声明背后的工作。我很困惑。我应该用哪一个来申报String

+0

你应该首先尝试搜索存在的问题检查的详细信息,有很多同样的回答问题。 –

+0

其实它似乎是一个嵌套的副本,因为那个也被标记为重复 – RSon1234

+0

并尝试用好的标点符号和语法来编写适当的单词。 –

回答

1

虽然字符串比较,你必须使用

if (s1.equals(s2)) { 
    do something; 
} 

不使用==

// These two have the same value 
s1.equals(s2) // --> true 

// ... but they are not the same object 
s1 == s2 // --> false 

// ... neither are these 
new String("test") == new String("test") // --> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object 
"tis is sample" == "tis is sample" // --> true 

// ... but you should really just call Objects.equals() 
Objects.equals(s1, new String("tis is sample")) // --> true 
Objects.equals(null, "tis is sample") // --> false 

此外,您可以从下面的代码http://rextester.com/GUR44534