How is the creation of a String using new() different from that of a literal ?

By | March 5, 2023

In Java, a String can be created in two ways: using the new() keyword or using a String literal.

When a String is created using the new() keyword, a new String object is created in memory every time, even if the content of the String is the same as an existing String. This means that two String objects with the same content will be stored in different memory locations, and comparing them using == operator will return false, even if their contents are the same.

Example:

String str1 = new String(“hello”);
String str2 = new String(“hello”);
System.out.println(str1 == str2); // false

On the other hand, when a String is created using a literal, the JVM checks if a String with the same content already exists in the String pool, which is a special area of memory used to store String literals. If a String with the same content already exists in the String pool, a reference to that String object is returned instead of creating a new String object. This means that two String literals with the same content will reference the same String object in the memory, and comparing them using == operator will return true.

Example:

String str3 = “hello”;
String str4 = “hello”;
System.out.println(str3 == str4); // true

In summary, the main difference between creating a String using new() and using a literal is that the former creates a new String object in memory every time, while the latter checks the String pool for an existing String with the same content before creating a new one. Therefore, using literals is a more efficient and recommended way for creating String objects in Java.

You May Also Like:

What are JVM, JRE and JDK in Java?
Differences between Java EE and Java SE
Encapsulation in Java
Abstraction in Java
Understating of Polymorphism in Java
Method Overloading or Static Polymorphism in Java
Method Overriding or Dynamic Polymorphism in Java
Understating of Inheritance in Java

Leave a Reply

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