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 |
Java interview questions on String Handling
- Why string objects are immutable in java?
- How many ways we can create the string object?
- Why java uses the concept of string literal?
- What is the basic difference between string, stringbuffer and stringbuilder object in java?
- How to create immutable class in java?
- What is the purpose of toString() method in java?
- Is string a keyword in java?
- Is string a primitive type or derived type?
- What is string constant pool in java?
- What are mutable and immutable objects in java?
- What is string intern in java?
- Can we call string class methods using string literals?