Ways of Creating a String
In Java, there are two primary ways to create a string:
1. String Literal
2. Using the new Keyword
Let's explore each method in detail.
1. String Literal
Creating a string using a string literal is the most common and convenient way. A string literal is a sequence of characters enclosed in double quotes ("").
Example
String str1 = "Hello";
String str2 = "Welcome to Java";
In the above example, str1 and str2 are string variables created using string literals. The Java compiler creates a String object with the specified value and assigns it to the variable.
2. Using the new Keyword
Another way to create a string is by using the new keyword along with the String constructor.
Example
String str3 = new String("Hello");
String str4 = new String("Welcome to Java");
In this case, str3 and str4 are string variables created using the new keyword and the String constructor. The constructor takes a string literal as an argument and creates a new String object with the specified value.
Both methods will create a String object, but there is a slight difference in how they are stored in memory, which we will discuss later.
Interfaces and Classes in Strings in Java
Java provides several interfaces and classes related to strings that offer various functionalities. Let's discuss the key interfaces and classes:
1. CharSequence Interface
The CharSequence interface is a generic interface that represents a sequence of characters. It provides methods to access and manipulate individual characters in the sequence. The String, StringBuffer, and StringBuilder classes all implement the CharSequence interface.
2. String Class
The String class is the most commonly used class for handling strings in Java. It represents an immutable sequence of characters.
Syntax
String str = "Hello";
3. StringBuffer Class
The StringBuffer class represents a mutable sequence of characters. It provides methods to modify the content of the string, such as appending, inserting, or deleting characters.
Syntax:
StringBuffer sb = new StringBuffer("Hello");
4. StringBuilder Class
The StringBuilder class is similar to the StringBuffer class but is designed for use in a single-threaded environment. It offers better performance compared to StringBuffer when thread safety is not required.
Syntax:
StringBuilder sb = new StringBuilder("Hello");
Both StringBuffer and StringBuilder are mutable, which means you can modify the content of the string without creating a new object.
These interfaces and classes provide a wide range of methods to perform operations on strings, such as concatenation, comparison, searching, substring extraction, and more. They form the foundation for working with strings in Java.
Immutable String in Java
In Java, strings are immutable, which means once a string object is created, its value cannot be changed. Whenever you perform any operation on a string that appears to modify it, a new string object is actually created with the modified value, leaving the original string unchanged.
Here's an example to illustrate string immutability:
Java
String str = "Hello";
str = str + " World";
System.out.println(str);

You can also try this code with Online Java Compiler
Run Code
Output:
Hello World
In the above code, when we concatenate " World" to the original string "Hello", a new string object is created with the value "Hello World". The original string "Hello" remains unchanged.
Memory Allocation of String
When you create a string using a string literal, the Java compiler checks the string pool in the heap memory to see if an identical string already exists. If it finds a match, it returns a reference to the existing string object. If no match is found, a new string object is created in the pool.
Example:
String str1 = "Hello";
String str2 = "Hello";
In this case, str1 and str2 will refer to the same string object in the string pool because they have the same value.
On the other hand, when you create a string using the new keyword, a new string object is always created in the heap memory, even if an identical string already exists in the pool.
Example:
String str3 = new String("Hello");
String str4 = new String("Hello");
Here, str3 and str4 will refer to different string objects in the heap memory, even though they have the same value.
Why did the String pool move from PermGen to the normal heap area?
In earlier versions of Java (prior to Java 7), the string pool was located in the PermGen (Permanent Generation) space of the JVM. However, starting from Java 7, the string pool was moved to the normal heap area. The main reasons for this change are:
1. PermGen space limitations: The PermGen space had a fixed size, and it was not easily resizable. If the string pool grew too large and exhausted the PermGen space, it could cause OutOfMemoryError exceptions. Moving the string pool to the normal heap area allowed for more flexible memory allocation and avoided such issues.
2. Garbage collection efficiency: The PermGen space was not typically garbage collected as frequently as the normal heap area. By moving the string pool to the normal heap, it became subject to regular garbage collection, which helped in reclaiming memory more efficiently when strings were no longer in use.
3. Simplification of memory management: Having the string pool in the PermGen space added complexity to memory management in the JVM. Moving it to the normal heap area simplified the memory layout and made it easier to manage and optimize.
4. Consistency with other objects: With the string pool in the normal heap area, strings are treated similarly to other objects in terms of memory allocation and garbage collection. This provides a more consistent and unified memory management model.
Frequently Asked Questions
What is the difference between String, StringBuffer, and StringBuilder in Java?
String is immutable, while StringBuffer & StringBuilder are mutable. StringBuffer is thread-safe, whereas StringBuilder is not. StringBuilder offers better performance for string manipulation in a single-threaded environment.
Why are strings immutable in Java?
Strings are immutable in Java for several reasons, including security, caching, synchronization, and performance optimization. Immutability allows string objects to be safely shared across multiple threads without the risk of unexpected modifications.
How does the string pool in Java work?
The string pool is a memory area in the heap where string literals are stored. When a string literal is created, the JVM checks the pool for an identical string. If found, a reference to the existing string is returned; otherwise, a new string object is created in the pool.
Conclusion
In this article, we have learned about strings in Java, which are objects that represent sequences of characters. We talked about different ways to create strings, like string literals and using the new keyword. We also discussed the CharSequence interface and the String, StringBuffer, and StringBuilder classes. Moreover, we looked into the concept of string immutability and how it affects memory allocation. Lastly, we covered the reasons behind the move of the string pool from PermGen to the normal heap area in Java 7.
You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360.
Also, check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.