In Java, how is creating a String using new() different from creating a text? Explain in detail, preferably from the source code perspective
In Java, there are two primary ways to create a String
: using the new
keyword and using string literals. While both methods ultimately create a String
object, they differ in how they manage memory and how they interact with the Java String pool.
new
When you create a String
using the new
keyword, you explicitly create a new instance of the String
class. For example:
String str1 = new String("Hello");
In this case, the following happens:
String
object is created in the heap memory, regardless of whether an equivalent string already exists in the String pool.String
constructor is called, which initializes the new object with the value "Hello".From the source code perspective, the String
class has a constructor that looks like this:
public String(String original) {
this.value = Arrays.copyOf(original.value, original.value.length);
this.hash = original.hash;
}
This constructor copies the character array from the original string to create a new String
object.
When you create a String
using a string literal, like this:
String str2 = "Hello";
The following occurs:
String
with the value "Hello" already exists.str2
will reference that existing String
object.String
object is created in the String pool, and str2
will reference that object.The String pool is a part of the Java heap memory that stores unique string literals. This mechanism helps save memory and improves performance by reusing immutable String
objects.
Memory Allocation:
new String(...)
: Always creates a new String
object in the heap, even if an equivalent string exists in the String pool.String
objects from the String pool if they already exist.Performance:
new String(...)
: Generally less efficient due to the overhead of creating a new object every time.Identity vs. Equality:
new String(...)
, they will not be equal using ==
because they reference different objects in memory.==
if they reference the same object in the String pool.String str1 = new String("Hello");
String str2 = "Hello";
String str3 = "Hello";
System.out.println(str1 == str2); // false, different objects
System.out.println(str2 == str3); // true, same object in the pool
System.out.println(str1.equals(str2)); // true, same content
In summary, using new String(...)
creates a new object in the heap memory, while using string literals leverages the String pool for memory efficiency. Understanding these differences is crucial for effective memory management and performance optimization in Java applications.