Search⌘ K
AI Features

Understanding Strings in Java

Explore how Java represents and manages strings as immutable objects, including efficient storage, memory usage, and key operations such as concatenation, formatting, and comparison. Understand correct string manipulation techniques to avoid common bugs and improve application text handling.

Text processing is fundamental to almost every application we build. Whether we are logging a username, processing a payment ID, or displaying a chat message, we rely on text. In Java, text is represented by the String class. While strings may look like simple primitive values, they are actually complex objects with unique behaviors regarding memory and modification.

In this lesson, we will explore how Java stores strings efficiently, why they cannot be changed once created, and how to manipulate them effectively.

The String object and creation

Unlike int or boolean, a String is a reference type, meaning it is an object. However, because strings are so common, Java provides a special shorthand syntax for creating them.

There are two ways to create a string:

  1. String literal: We enclose text in double quotes ("Hello"). Java optimizes this by storing the string in a special memory area called the String Pool. If we use the same literal twice, Java reuses the existing instance to save memory.

  2. new keyword: We can explicitly create a new object using new String("Hello"). This forces Java to create a distinct object on the heap, bypassing the pool’s optimization. We rarely do this in practice, but understanding the difference is vital for debugging.

Java 25
public class StringCreation {
public static void main(String[] args) {
// Method 1: String Literal (Recommended)
// Stored in the String Pool
String s1 = "Java";
String s2 = "Java"; // Reuses the same object as s1
// Method 2: Using 'new' (Avoid unless necessary)
// Forces a new object on the Heap, outside the Pool
String s3 = new String("Java");
// Comparing references (addresses), NOT content
System.out.println("s1 == s2: " + (s1 == s2)); // true (Same pool object)
System.out.println("s1 == s3: " + (s1 == s3)); // false (Different objects)
}
}
  • Lines 5–6: We create two string variables using literals. Because the text is identical, s1 and s2 point to the exact same memory address in the String Pool.

  • Line 10: We use the new keyword. This forces the JVM to create a brand new object in standard heap memory, even though the content ("Java") is the same.

  • Lines 13–14: We print the result of reference comparisons. s1 == s2 is true because they share the same address. s1 == s3 is false because s3 is a completely separate object.

This diagram illustrates how literals share references in the String Pool, whereas objects created with new occupy distinct ...