JAVA: What is the String Literal Pool?

class a { public static String a = "hello"; }
class b { public static String b = "hello"; }
class c {
  public void static main(String args[]) {
    System.out.println(A.a = B.b); // true
  }

At compile-time:
  Step 1: compile class a, tag "hello" as a special variable that can be loaded into the literal pool during run-time.
  Step 2: compile class b, tag "hello" as a special variable that can be loaded into the literal pool during run-time.

At run-time in main:
  Step 1: load String literal from class A ("hello") into literal pool
  Step 2: attempt to load String literal from class B ("hello") into literal pool.
  Step 3: "hello" already exists, return existing reference to "hello" in the literal pool


Tricking the Compilation for the String Literals

class c {
  public void static main(String args[]) {
    String a = "a";
    String b = "b";
    String c = "a" + "b";
    String d = a + b;
    System.out.println(c==d); // false, because a and b are variables subject to change
  }
}

class d {
  public void static main(String args[]) {
    final String a = "a";
    final String b = "b";
    String c = "a" + "b";
    String d = a + b;
    System.out.println(c==d); // true, because a and b are constants!
  }
}

class e {
  public void static main(String args[]) {
    String c = "a" + "b";
    String d = "ab";
    System.out.println(c==d); // true, because both RHS are constants!
  }
}

String a = "hello";
String b = "hello";
final String c = new String ("hello");
String d = a.intern();

a == b // true
a == c // false
a == d // true


No comments: