String Initialisation in Java — IMORTANT Interview Question

Abhinay Gupta
2 min readJun 9, 2023

--

In Java, there are two types of string initialization:

1. String Literal:
String literals are created by enclosing the sequence of characters in double quotes (e.g., `”Hello”`). When the Java compiler encounters a string literal, it checks if an identical string already exists in the string pool (a pool of unique string literals stored in memory). If it does, the compiler references that existing string from the pool. If not, the compiler creates a new string object in the pool. Subsequent string literals with the same value will reference the same object in the string pool. String literals are immutable, meaning their values cannot be changed.

Example:

String str1 = "Hello"; // String literal
String str2 = "Hello"; // Reference to the existing string object in the string pool

2. String Object:
Strings can also be created using the `new` keyword, which creates a new instance of the `String` class. When a string object is created using the `new` keyword, it allocates memory in the heap to store the string’s value. Each time a new object is created using `new`, even if the value is the same as an existing string, a new memory location is allocated. String objects created with `new` are not stored in the string pool and are separate instances. These objects are mutable, meaning their values can be changed.

Example:

String str3 = new String("Hello"); // String object created with the new keyword
String str4 = new String("Hello"); // Another separate instance of the string object

It’s important to understand the distinction between string literals and string objects. String literals offer better memory efficiency and performance due to string interning, where identical string literals are reused. String objects, on the other hand, have their own memory space and can be modified, but they require more memory and have slightly lower performance compared to string literals.

When working with string values that won’t change, using string literals is recommended. If you need to manipulate the string or create dynamic strings, using string objects is appropriate.

--

--

Abhinay Gupta

Exploring personal growth, tech, and culture through engaging storytelling | Inspiring and connecting with readers worldwide.