1

I came across a question asking the output of the below:

    String s1 = "String 1";
    String s2 = "String 2";

    String s3 = s1 + s2;
    String s4 = "String 1" + "String 2";

    System.out.println(s3==s4);

Output - false

Now, since the strings are not created using new operator, so the objects are created in the string pool, so as per my understanding s1 + s2 and "String 1" + "String 2" should be equal, and s3==s4 should be true.

But it is not happening in real. Can any one please explain this?

Vikas
  • 107
  • 1
  • 10

2 Answers2

4

The concatenation is happening at runtime, unless both operands are compile-time constant expressions.

Put a final modifier before s1 and s2, and the result will be true, because the compiler will simply replace

String s3 = s1 + s2;

by

String s3 = "String 1String 2";

If you don't, a new String is created at runtime, by appending both strings to a StringBuilder and getting the result.

Note that, although that is interesting from an intellectual point of view, in practice, you shouldn't care about that performance optimization, and always compare Strings with equals().

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
1

This line compare memory addresses of two strings. Because of both are separate objects and output will be false.

s3==s4

You need to compare using equals()

System.out.println(s3.equals(s4));

equals() is compare value of object not address.

Blasanka
  • 21,001
  • 12
  • 102
  • 104