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

3
  • You should try searching existing questions first, there are many same answered questions. Commented Oct 1, 2017 at 4:48
  • Actually it appears to be a nested duplicate because that one was also marked duplicate Commented Oct 1, 2017 at 4:49
  • And try to write proper words with nice punctuation and grammar. Commented Oct 1, 2017 at 4:50

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.