Java
Module 6: Java Strings & StringBuilderBeginner24 min read

Java Strings, Immutability & String Pool

Understand why Java Strings are immutable, how the String Constant Pool saves memory, and why .equals() must be used instead of ==.

Key Takeaways & Core Concepts
  • == compares memory addresses (whether both variables point to the exact same object).
  • .equals() compares character content. Always use .equals() (or .equalsIgnoreCase()) to compare string values!
  • Calling s.toUpperCase() or s.trim() without assigning the return value—String methods always return a new String.

Introduction

java.lang.String is one of the most heavily used classes in Java. Every String is immutable—once constructed, its underlying character bytes (stored as compact Latin-1 or UTF-16 byte arrays since Java 9) can never change.

String Pool, `.equals()` & Common Methods
1public class Main {
2 public static void main(String[] args) {
3 String s1 = "Java";
4 String s2 = "Java";
5 String s3 = new String("Java");
6
7 System.out.println("s1 == s2: " + (s1 == s2));
8 System.out.println("s1 == s3: " + (s1 == s3));
9 System.out.println("s1.equals(s3): " + s1.equals(s3));
10 System.out.println("Substring: " + "CodeZov".substring(0, 4).toUpperCase());
11 }
12}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
12 lines
Note: `s3` is explicitly allocated outside the String Pool via `new String(...)`, so `s1 == s3` is `false` while `s1.equals(s3)` is `true`.

Why Are Strings Immutable?

  1. 1
    String Constant Pool (SCP): Identical string literals share a single pooled object in Heap memory, drastically reducing RAM usage across thousands of classes.
  2. 2
    Thread Safety: Immutable objects can be shared freely across threads without locks or race conditions.
  3. 3
    Security: File paths, database URLs, and network hosts cannot be mutated after security checks pass.
  4. 4
    HashCode Caching: String caches its hashCode() once, making it an ultra-fast HashMap key.

Reference Equality (==) vs Content Equality (.equals())

  • == compares memory addresses (whether both variables point to the exact same object).
  • .equals() compares character content. Always use .equals() (or .equalsIgnoreCase()) to compare string values!

Common Mistakes

  • Calling s.toUpperCase() or s.trim() without assigning the return value—String methods always return a new String.
Practice & AssessmentJava Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)