-2

What is the difference between these two string declarations?

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

When I check s1==s2 it says false.

Why is it false?

Could you also explain the working behind these two declarations. I am so confused with it. Which one should I use to declare a String?

user207421
  • 305,947
  • 44
  • 307
  • 483
Eddy
  • 67
  • 7

1 Answers1

1

While string comparison, you have to use

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

not use ==

// 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

In addition you can check details from below code http://rextester.com/GUR44534

Am_I_Helpful
  • 18,735
  • 7
  • 49
  • 73
Dr. X
  • 2,890
  • 2
  • 15
  • 37