0
String a = "x";
String b = a + "y";
String c = "xy";
System.out.println(b==c);

Why it prints false?

As per my understanding "xy"(which is a+"y") will be interned and when variable c is created compiler will check if literal "xy" is present in String constant pool if present then it will assign same reference to c.

Note : I am not asking equals() vs == operator.

jason0x43
  • 3,363
  • 1
  • 16
  • 15
  • `"xy"` is interned, but the result of `a+"y"` isn't, nor is the interned `"xy"` used as that result, because `a` isn't final. – Andy Turner Oct 08 '17 at 08:58
  • 1
    Possible duplicate of [Comparing strings with == which are declared final in Java](https://stackoverflow.com/questions/19418427/comparing-strings-with-which-are-declared-final-in-java) – Ravi Oct 08 '17 at 09:02
  • Besides the other answers: also try to,avoid to rely on it. It is brittle if code is reused. – eckes Oct 08 '17 at 09:07

2 Answers2

1

If a String is formed by concatenating two String literals it will also be interned.

String a = "x";
String b = a + "y"; // a is not a string literal, so no interning
------------------------------------------------------------------------------------------
String b = "x" + "y"; // on the other hand, "x" is a string literal
String c = "xy";

System.out.println( b == c ); // true

Here is a commonly found example on string interning in Java

class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";

        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}

class Other { static String hello = "Hello"; }

followed by it's output

true
true
true
true
false
true
Valdrinium
  • 1,398
  • 1
  • 13
  • 28
0

The reason that "xy", as is assigned to c, is added to the string pool (used by intern) straight away is because the value is known at compile time.

The value a+"y" is not known at compile time, but only at run time. Because intern is an expensive operation, that is not normally done unless the developer codes for it explicitly.

Joe C
  • 15,324
  • 8
  • 38
  • 50