String Handling in Java

String Handling in Java - Literals vs new Keyword, Immutability & String Pool (2026)

String Handling in Java - Complete Guide

As you know, whenever you take input or output from the user in Java, you always get String type data. In Java, String is a predefined class. The JVM creates new memory for String all the time - let's understand how JVM manages memory.

String Handling Title

What is String in Java?

  • String is a group of characters or sequence of characters.
  • String is a predefined class in Java which exists in java.lang package.
  • String is a final class in Java - it can never be inherited.
  • String class implements Serializable, Comparable, CharSequence interfaces etc.
  • String objects are immutable - once created, they can never be changed.
  • String object is always represented by double quotes.
  • You can create String objects in two ways:
    1. Using Literals Concept
    2. Using new Keyword

Using Literals Concept

You can create String literals with double quotes:

String name = "Deep Singh";

In case of literals, one reference variable and one object is created.

When you use String literals, JVM first checks in String Pool (Constant Pool). If that object exists, it returns the same address to the reference variable.

Example:

String first = "Deep";
String last = "Singh";
String lname = "Singh"; // Points to same object as last, no new object created
String literals String Pool diagram

Using new Keyword

You can create String instance with new keyword:

String name = new String("Ashok Singh");

In case of new keyword, one reference variable and two objects are created - one inside String Pool (Constant Pool) and another inside Heap Area.

By default, it points to Heap Area address.

Example:

String name = new String("Ashok Singh");
String new keyword heap diagram

String Objects are Immutable - Example

String name = "Deep";
name.concat("Singh");
System.out.println(name);
Result: Deep (Not Deep Singh)

Why? Because String is immutable. concat() creates a new object "Deep Singh" in pool, but reference variable name still points to old object "Deep". To get new value, you must assign: name = name.concat("Singh");

Conclusion

String Pool saves memory by reusing literals. Use literals (String s = "Deep") for memory efficiency. Use new String() only when you explicitly need heap object. Remember String immutability - any modification creates new object.

Next: StringBuffer vs StringBuilder, String Methods, String Comparison (== vs equals)

2 comments:

Chandan said...

Very nice sir but am dout in Literals
Can you explan it....

Chandan said...

Very nice sir but am dout in Literals
Can you explan it....