-4

The below program outputs false

    String s1="a";
    String s2="b";
    String s3=s1+s2;
    String s4="ab";

    if(s3==s4)
    {
        System.out.println("true");
    }
    else
    {
        System.out.println("false");
    }

and this code outputs true

String s3="a"+"b";
  String s4="ab";

  if(s3==s4)
  {
      System.out.println("true");
  }
  else
  {
      System.out.println("false");
  }

Shouldn't the output in first case be true? As while creating String s4="ab" there is already an object with value "ab" in the string constant pool.

rajkumar.11
  • 313
  • 2
  • 9
  • 8
    Why are people so obsessed with the string constant pool and how the compiler chooses to implement String concatenation? The only thing you need to know is to never compare Strings with `==`. – Thilo Jul 30 '19 at 10:30
  • 1
    See also https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java –  Jul 30 '19 at 10:32
  • @Thilo i was asked this question in an interview so i asked – rajkumar.11 Jul 30 '19 at 10:38
  • @ Lutz the redirected question does not answer the actual question – rajkumar.11 Jul 30 '19 at 10:40
  • 2
    If I was asked this in an interview my answer would be the same: "The only thing you need to know is to never compare Strings with `==`". If they are interviewing for business application developers and not compiler writers they are asking the wrong question. – Thilo Jul 30 '19 at 10:40
  • @rajkumar.11 Maybe this one helps? https://stackoverflow.com/questions/45165496/java-string-concatenation-and-interning – Thilo Jul 30 '19 at 10:43

1 Answers1

3

In Java, you want to use .equals() instead of == to compare strings. Try the following.

String s1="a";
String s2="b";
String s3=s1+s2;
String s4="ab";

if(s3.equals(s4))
{
    System.out.println("true");
}
else
{
    System.out.println("false");
}
Adam Lerman
  • 3,369
  • 9
  • 42
  • 53
  • i am aware of using equals when we we want to compare the string values and == when we want to compare objects but my question is different. – rajkumar.11 Jul 30 '19 at 10:35