Java Strings Explained in Depth: String Pool, Immutability, Memory Management & Examples

Java Strings Explained in Depth: String Pool, Immutability, Memory Management & Examples

6 min read

1. A String is a sequence of characters

Like an array of char, a String has positions starting at 0:

Plain text
 text:   J   A   V   A       2   1 index:  0   1   2   3   4   5   6
Java
public class Main {    public static void main(String[] args) {        String s = "JAVA 21";        System.out.println(s.length());      // 7 (method, so brackets!)        System.out.println(s.charAt(0));     // J        System.out.println(s.charAt(s.length() - 1));   // 1        for (int i = 0; i < s.length(); i++) {            System.out.print(s.charAt(i) + "-");        }    }}

2. The essential String methods

Method

Returns

Example with s = "Hello World"

Result

length()

int

s.length()

11

charAt(i)

char

s.charAt(4)

'o'

substring(a, b)

String from index a up to (not including) b

s.substring(0, 5)

"Hello"

substring(a)

String from a to the end

s.substring(6)

"World"

indexOf(x)

first position of x, or -1

s.indexOf("o")

4

lastIndexOf(x)

last position, or -1

s.lastIndexOf("o")

7

contains(x)

boolean

s.contains("World")

true

startsWith(x) / endsWith(x)

boolean

s.endsWith("ld")

true

toUpperCase() / toLowerCase()

String

s.toUpperCase()

"HELLO WORLD"

strip()

String without leading/trailing spaces

" hi ".strip()

"hi"

replace(a, b)

String with every a replaced by b

s.replace("l", "L")

"HeLLo WorLd"

split(sep)

String array

s.split(" ")

["Hello", "World"]

isEmpty() / isBlank()

boolean

" ".isBlank()

true

equals(x) / equalsIgnoreCase(x)

boolean

s.equals("hello world")

false

compareTo(x)

int: negative, 0 or positive (dictionary order)

"apple".compareTo("banana")

negative

repeat(n)

String

"ab".repeat(3)

"ababab"

Also useful: String.join("-", "a", "b", "c") gives "a-b-c", and String.valueOf(42) turns any value into text.

For individual characters, the Character tools help: Character.isDigit(c), Character.isLetter(c), Character.isUpperCase(c), Character.toUpperCase(c), Character.isWhitespace(c).

3. Immutability: Strings never change

A String object can never be modified after it's created. Every method that seems to change a String actually creates a new String.

Java
public class Main {    public static void main(String[] args) {        String name = "riya";        name.toUpperCase();              // creates "RIYA", then throws it away        System.out.println(name);        // riya: unchanged!        name = name.toUpperCase();       // store the new String back in the variable        System.out.println(name);        // RIYA    }}

4. The String pool, and why == fails

Because Strings never change, Java can safely share identical text. String literals (text written in quotes in code) are stored once in a special area called the String pool:

Java
import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        String a = "java";        String b = "java";                  // reuses the same pooled object        String c = new String("java");      // forces a brand-new object        System.out.print("Type java: ");        String d = sc.nextLine();   // text built at runtime: a new object        System.out.println(a == b);          // true: same object        System.out.println(a == c);          // false: different objects        System.out.println(a == d);          // false        System.out.println(a.equals(c));     // true: same characters        System.out.println(a.equals(d));     // true    }}
== compares references (same object?); equals compares the characters.

== asks "are these the same object?" (do both arrows point to the same place?). .equals() asks "do these contain the same characters?" For text, you almost always want the second question.

5. StringBuilder: building text efficiently

Because Strings are immutable, this loop creates a new String object every round (10,000 of them):

Java
String result = "";for (int i = 0; i < 10000; i++) {    result = result + i;   // each + makes a new String and copies all the old text}

StringBuilder is a changeable text container built for this job:

Java
public class Main {    public static void main(String[] args) {        StringBuilder sb = new StringBuilder();        for (int i = 1; i <= 5; i++) {            sb.append(i).append(", ");        }        sb.setLength(sb.length() - 2);        // remove the last ", "        System.out.println(sb);               // 1, 2, 3, 4, 5        StringBuilder word = new StringBuilder("level");        System.out.println(word.reverse());   // level        String finalText = sb.toString();     // convert back when needed    }}

Useful StringBuilder methods: append, insert(index, x), deleteCharAt(index), reverse(), setCharAt(index, c), toString().

Rule of thumb: a few + joins are fine. Joining inside a loop? Use StringBuilder.

6. Text blocks

For multi-line text, use triple quotes:

Java
String menu = """        1. Add student        2. List students        0. Exit        """;System.out.print(menu);

7. Worked problems

Reverse a String

Java
static String reverse(String s) {    StringBuilder sb = new StringBuilder();    for (int i = s.length() - 1; i >= 0; i--) {        sb.append(s.charAt(i));    }    return sb.toString();    // Shortcut: return new StringBuilder(s).reverse().toString();}

Count vowels and consonants

Java
static void countLetters(String s) {    int vowels = 0, consonants = 0;    for (char c : s.toLowerCase().toCharArray()) {        if (Character.isLetter(c)) {            if ("aeiou".indexOf(c) >= 0) vowels++;            else consonants++;        }    }    System.out.println("Vowels: " + vowels + ", consonants: " + consonants);}

toCharArray() turns the String into a char[] so we can use for-each. "aeiou".indexOf(c) >= 0 is a neat way to check membership.

Anagram check ("listen" and "silent")

Java
static boolean isAnagram(String a, String b) {    char[] x = a.replace(" ", "").toLowerCase().toCharArray();    char[] y = b.replace(" ", "").toLowerCase().toCharArray();    Arrays.sort(x);    Arrays.sort(y);    return Arrays.equals(x, y);}

Common mistakes

  • s.length instead of s.length() (and the opposite for arrays).

  • Calling toUpperCase(), replace() or strip() without storing the result.

  • Comparing text with ==.

  • substring(2, 5) gives 3 characters (indexes 2, 3, 4), not 5. The end index is excluded.

  • Calling methods on a String that is null: this crashes with NullPointerException.

Interview questions

Why are Strings immutable in Java?

For security (values like file paths and credentials can't be changed after validation), thread safety, and to allow the String pool to share instances safely. It also allows caching the hash code, which makes Strings efficient as keys in hash-based collections.

What is the String pool?

A special area in the heap where string literals are stored once and shared. Two identical literals refer to the same pooled object. new String("x") always creates a new object outside the pool; intern() returns the pooled version.

What is the difference between String, StringBuilder and StringBuffer?

String is immutable. StringBuilder is mutable and fast but not thread-safe. StringBuffer is mutable and thread-safe (synchronised) but slower. Use StringBuilder unless several threads modify the same buffer.

How many objects does String s = new String("hello"); create?

Up to two: the literal "hello" in the pool (if it isn't already there) and a new String object on the heap that s refers to.

Practice

  1. easy Check whether a word is a palindrome, ignoring case ("Madam").

  2. easy Count the words in a sentence (watch out for multiple spaces: split("\\s+") splits on one or more whitespace characters).

  3. easy Capitalise the first letter of every word: "java is fun" → "Java Is Fun".

  4. medium Print the frequency of each character in a word (use an int[26] array for lowercase letters).

  5. medium Remove duplicate characters, keeping the first occurrence: "programming" → "progamin".

  6. medium Check whether one string is a rotation of another ("abcd" and "cdab"). Hint: look inside a + a.

  7. hard Compress a string: "aaabbcccc" → "a3b2c4". Return the original if the compressed version isn't shorter.

© 2026 Rohit Parihar. All rights reserved.

RP

Discussion

?