java中的字符串声明

时间:2017-10-01 04:44:17

标签: java string

这两个字符串声明之间有什么区别?

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

当我检查s1==s2时,它会显示false

为什么是false

你能解释这两个声明背后的工作吗?我很困惑。我应该使用哪一个来声明String

1 个答案:

答案 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

中的详细信息