0

In this program the answer/output is false can you explain how is it so?

I have tried the code and i got output "false"

class eq
{
public static void main(String args[])
{
String s1 = “Hello”;
String s2 = new String(s1);
System.out.println(s1==s2);
}
}

i expect the output to be "true"

  • You cannot use == to compare String types as they are not primitive data types; you must use .equals() – Musilix Jun 15 '19 at 21:34

1 Answers1

4

In java you must use .equals to compare strings. Try the following code System.out.println(s1.equals(s2));

  • but why is it showing false when i used == – MohammadFahad Jun 15 '19 at 21:37
  • @MohammadFahad Read the duplicate post. `==` checks that they're literally the same string, not that the two strings are equal according to their value. – Carcigenicate Jun 15 '19 at 21:38
  • == compares memory addresses, not string contents. So s1==s1 will be true but s1==s2 will be false since they are at different memory addresses. Use .equals to compare the strings' actual value – Jeremy Berchtold Jun 15 '19 at 21:39
  • You are creating two different String objects referenced via the references "s1" and "s2". "==" asks the question "are these two references pointing to the same object". In your case, the answer is NO..."s1" and "s2" are pointing at Different Objects representing the Same String Value. `.equals()` asks if the two references refer to the same String Value, to which the answer is YES. – CryptoFool Jun 15 '19 at 21:40
  • If instead of `String s2 = new String(s1);` you did `String s2 = s1;`, then your "==" test would return `true`. – CryptoFool Jun 15 '19 at 21:42
  • BTW, it is not unusual or unreasonable for you to have this question. It's a quirk somewhat unique to Java. In fact, Kotlin, one of the up and coming replacements for Java, "fixes" this. In Kotlin, you'd get the behavior you're expecting. To keep the Java behavior available, Kotlin defines "===" that acts like Java's "==". (I don't know Groovy or Scala, two other prominent alternatives to Java, but my guess is that they both remedy this "flaw" in a similar way). – CryptoFool Jun 15 '19 at 21:47