String Constants

The String Constants are stored in the String Literal Pool. They are actually loaded into the pool during the class loading operation itself.

Java Language Specification discusses about the same here.

JLS says in 3.10.5 String Literals
Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.

Strings computed by concatenation at run time are newly created and therefore distinct.

Sample Program to demonstrate:

class Main {
    public static void main(String[] args){
        String hello = "hello";
        String lo = "lo";
        System.out.println(hello == "hel" + "lo"); // true
        System.out.println(hello == "hel" +  lo ); // false

The output of the program is


Twist: try changing the string variable "lo" to final. :)

Answer is : both will be true as the final variable is again treated as a compile time constant. Twist is given by Burkhard Hassel (bartender in Javaranch).

A thought on +, concat() methods

An excellent discussion is here

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.