DEV Community

Quipoin
Quipoin

Posted on

Why Java Strings Are Immutable — And Why It Matters


Strings look simple…

But Java Strings hide some very important concepts:

  • Immutability
  • String Pool
  • Memory optimization

And interviewers LOVE asking about them.

What is a String?

A String is a sequence of characters.

In Java:

  • Strings are objects of the String class.

String name = "Java";

Why Strings Are Immutable

Once a String is created:

  • Its value cannot be changed.

Example:

String s = "Hello";
s = s + " World";

This creates:

  • Old object → "Hello"
  • New object → "Hello World"

The original string remains unchanged.

String Pool Explained

Java stores string literals inside a special memory area called the String Pool.

String s1 = "Hello";
String s2 = "Hello";

  • Both variables point to the same pooled string.

This saves memory and improves performance.

Important String Methods

String str = " Java DSA ";

str.length();
str.trim();
str.toUpperCase();
str.charAt(2);
str.indexOf("DSA");
str.substring(2, 9);

equals() vs ==

This is one of the most common beginner mistakes.

String a = new String("Java");
String b = new String("Java");

System.out.println(a == b); // false
System.out.println(a.equals(b)); // true

Why?

  • == compares references
  • equals() compares content

Java Strings are designed this way for:

  • Security
  • Memory optimization
  • Thread safety

  • Strings are immutable

  • String literals use pooling

  • Use equals() for comparison

For More Learning: https://www.quipoin.com/tutorial/data-structure-with-java/string-introduction

Top comments (0)