String literal in java

Literal: A literal represents any constant value of boolean, character, numeric, or string type. Example: “Jai”, 11 etc.

String Literal Syntax:

String stringReference= “Value”;

String Literal Example:

public class Main {
 
    public static void main(String[] args) {
        String myName= "Jai";
        System.out.println(myName);
    }
}

Output:

Jai

Why java uses the concept of string literal?

String literal concept is used to make Java more memory efficient. As multiple references can point to one value in string pool and no new object will be created if it already exist in string constant pool.

String literal vs String object

Main difference between String literal and String object is that, in case of String literal new instance will not be created if string value is already present in the string constant pool but in case of string object, a new string instance will be created whether the value is present in the string pool or not.

String Literal vs String Object Example:

public class Main {
 
    public static void main(String[] args) {
        //String literals
        String testString1 = "test";
        String testString2 = "test";
 
        System.out.println(testString1 == testString2);// true
 
        //String Object
        testString2 = new String("test");
        System.out.println(testString1 == testString2);// false
        System.out.println(testString1.equals(testString2)); // true
    }
}

Output:

true 
false
true

Read more on string handling

Java interview questions on String Handling

Content Protection by DMCA.com
Please Share