JDeveloper JDeveloper - 2 months ago 24
Java Question

String Constant Pool vs String pool

I am confused about these two things. I need a help. Please clear my doubt, whether String Constant Pool and String pool both are same concept. I faced this question on interview. I have already read lot of sites and blogs but, my doubt is not cleared.Please clear my doubts.

Thanks in Advance.

Answer

Both are the same thing. String Constant Pool contains constant string objects. Constant can be defined as String object holds the value at compile time. For more refer JLS.

    String s="abc";
    String s1="def";
    String s2=s+"def";
    String s3="abc"+"def";
    System.out.println(s2==s3); // print false

But if you make s as final then

    final String s="abc";
    String s1="def";
    String s2=s+"def";
    String s3="abc"+"def";
    System.out.println(s2==s3); // print true

In above case s3 is a compile time constant as s is final .