1

The value of s2 and s3 is "ab" and this string is stored in string pool. As per doc s2==s3 should return true but it is returning false. Why?

 public class Sample {
      public static void main(String[] args) {
      String s="a";
      String s1="b";
      String s2=s+s1;
      String s3="ab";
      System.out.println(s2==s3);
   }
}
user1773579
  • 122
  • 1
  • 9

2 Answers2

1

According to the Java Language Specification §15.18.1

15.18.1 String Concatenation Operator +

If only one operand expression is of type String, then string conversion (§5.1.11) is performed on the other operand to produce a string at run time.

The result of string concatenation is a reference to a String object that is the concatenation of the two operand strings. The characters of the left-hand operand precede the characters of the right-hand operand in the newly created string.

The String object is newly created (§12.5) unless the expression is a constant expression (§15.28).

+ will always produce a new string, unless the expression is constant. One example of a constant expression is "a" + "b". Your expression is not constant because it contains non-final variables.

This is stated even more clearly in §12.5:

Execution of a string concatenation operator + (§15.18.1) that is not part of a constant expression (§15.28) always creates a new String object to represent the result.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
-1

Sure both s2 and s3 equal to "ab".

And sure the "ab" String is into the String pool, because you had that String as a literal in your code. Which also means that s3 is taken from the String pool since you're assigning the said literal to it.

But why would you think that s + s1 would pull the resulting String out of the String pool? It wouldn't.

kumesana
  • 2,495
  • 1
  • 9
  • 10