String Pool : String instances created by concatenating two or more String literals

(Series on String Pool : Part 3 of 4)

Let’s hear the conversation between a programmer and JVM on this topic –


Programmer : “Where do the String instances created by concatenating two or more literal values reside? Are they placed in the String Pool?”

“Here’s a quick example. Will the variable ‘val2’ refer to the String instance referred to by variable ‘val1’:”

class EJavaGuru {
    public static void main(String args[]) {
        String val1 = "Fax";
        String val2 = "F" + "a" + "x";
        System.out.println(val1 == val2);
    }
}

 

JVM : “The preceding code will output true.”

 

Programmer : “What happens, if I modify the preceding code, so that one of the String literal is stored in a variable, as follows:”

 

class Test {
    public static void main(String args[]) {
        String val1 = "Fax";
        String temp = "x";
        String val2 = "F" + "a" + temp;
        System.out.println(val1 == val2);
    }
}

 

JVM : “It will output false. To keep it simple, I only place compile time constants in the String pool.”

 

Programmer : “What about the following modified code then?”

 

class EJavaGuru {
    public static void main(String args[]) {
        String val1 = "Fax";
        final String temp = "x";
        String val2 = "F" + "a" + temp;
        System.out.println(val1 == val2);
    }
}

 

JVM : “The preceding code is good to output true, because the value stored in the variable ‘temp’ is now a compile time constant.”

Programmer : : “Thanks for clearing my doubts.”

Leave a Reply

Your email address will not be published. Required fields are marked *