Java-new String vs String literals

new String vs String literals

When you create String object using new¬†operator, it always create a new object in heap(one of memory section). On the other hand, if you create object using string literal, it may return an existing object from String pool(one of memory section), if it’s already exists. Otherwise it will create a new string object and put in string pool for future re-use.

Program

Program Source

public class Javaapp {

    public static void main(String[] args) {

        String str1 = new String("hajsof");
        
        String str2 = new String("hajsof");
        
        String str3 = "hajsof";
        
        String str4 = "hajsof";

        if (str1 == str2) 
        {
            System.out.println("str1==str2 is true");
        } else {
            System.out.println("str1==str2 is false");
            System.out.println("Because == tests object references only");
        }

        if (str3 == str4) 
        {
            System.out.println("str3==str4 is true ");
            System.out.println("Because both references pointing to same object.");
        } else {
            System.out.println("str3==str4 is false");
        }
    }
}

Leave a Comment