String Vs String Literal in Java

 Declaring String in Java:

        You can declare string in Java in two ways:
                1. Using String Literal
                2. Using String() Object

1. Using String Literal:
            
                            String str = "hello"
            This is a string literal. To store String literal JVM creates a reference internal pool. Which means
first it will search if the value provided to the string variable exists in internal pool or not.
        If the value already exists in the internal pool, it will not allocate a new memory location to the newly created variable instead it provides reference to the variable of already existing value.

Consider the following example:
                             String str1 = "google"
                             String str2 = "google"

                             System.out.println(str1 == str2);   //Output: true
    
            It will print true since both str1 and str2 referencing to the same value/memory location.

2. Using String() Object:
                                String str = new String("google");
                String created using String() object forces JVM to create new string reference even if value "google" already exists in the reference pool.

                                String str1 = new String("google");
                                String str2 = new String("google");
        
                                System.out.println(str1 == str2);   //Output: false
               
            It will print false since both str1 and str2 referencing to the different memory location.
Hence to compare values of string object, you can use equals() method. 
                                System.out.println(str1.equals(str2));  //Output: true

Note: Peformance of string literal is better than String() object, because String object will always create a new reference.








Comments

Popular Posts