Stringconstants

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

true
false

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 http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=042360&p=1

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