Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 23: Strings and the String Pool in Java

Java for Beginners · Module 5: Data and Methods


🎯 Text in Java

Names, messages, passwords, addresses: most real data is text. Java stores text in the String class. A String is not a primitive type (Lesson 8). It is an object, and that brings useful methods and a few surprises that this lesson explains.

📌 A String is an immutable (unchangeable) sequence of characters. Literals in double quotes are stored in a shared area called the string pool.

1️⃣ Creating and Using Strings

String greeting = "Hello, Java!";
H
0
e
1
l
2
l
3
o
4
,
5
␣
6
J
7
a
8
v
9
a
10
!
11
A String is a sequence of characters, indexed from 0. length() = 12, charAt(1) = e.

Figure 1: A String is a row of characters with indexes.

Program 1: String basics

public class StringBasics {
    public static void main(String[] args) {
        String name = "Java";
        String greeting = "Hello, " + name + "!";
        System.out.println(greeting);
        System.out.println("length = " + greeting.length());
        System.out.println("charAt(1) = " + greeting.charAt(1));

        char[] letters = {'J', 'a', 'v', 'a'};
        String fromChars = new String(letters);
        System.out.println(fromChars);

        String empty = "";
        String nothing = null;
        System.out.println("empty length = " + empty.length());
        System.out.println("nothing = " + nothing);
    }
}
🖥️ Output:
Hello, Java!
length = 12
charAt(1) = e
Java
empty length = 0
nothing = null
  • Strings are written in double quotes. (A single character uses single quotes: 'A'.)
  • + joins Strings. This is called concatenation.
  • length() has brackets for a String, but length has none for an array (Lesson 21).
  • charAt(i) gives the character at index i, counting from 0.
  • An empty String "" has length 0. A null String means “no String object at all”. They are different.

2️⃣ The String Pool

String pool (shared area in the heap)
“java”
a ➜ pool “java”   b ➜ pool “java”  (same object)
c = new String("java") ➜ separate “java” object on the heap

Figure 2: Literals share one pooled object. new String(...) makes another.

Java saves memory by keeping one copy of each literal. When you write "java" twice, both variables point to the same pooled object. new String("java") forces a new, separate object.

public class PoolDemo {
    public static void main(String[] args) {
        String a = "java";
        String b = "java";
        String c = new String("java");
        String d = new String("java").intern();

        System.out.println("a == b          : " + (a == b));
        System.out.println("a == c          : " + (a == c));
        System.out.println("a.equals(c)     : " + a.equals(c));
        System.out.println("a == c.intern() : " + (a == c.intern()));
        System.out.println("a == d          : " + (a == d));
    }
}
🖥️ Output:
a == b : true
a == c : false
a.equals(c) : true
a == c.intern() : true
a == d : true
  • a == b is true: both literals refer to the same pooled object.
  • a == c is false: c is a different object, even though its text is the same.
  • a.equals(c) is true because equals compares the characters.
  • intern() returns the pooled copy, so c.intern() is the same object as a.
  • Rule: compare Strings with equals(), never with ==.

3️⃣ Comparing Strings

CheckCodeMeaningResult for “java” vs new String(“java”)
Same object?a == ccompares referencesfalse
Same text?a.equals(c)compares characterstrue
Same text, ignore case?a.equalsIgnoreCase(c)ignores capitalstrue
Dictionary ordera.compareTo(c)negative, 0 or positive0

Figure 3: Comparing Strings: == versus equals.

public class Compare {
    public static void main(String[] args) {
        String x = "apple";
        String y = "Apple";
        System.out.println("equals           : " + x.equals(y));
        System.out.println("equalsIgnoreCase : " + x.equalsIgnoreCase(y));
        System.out.println("compareTo        : " + x.compareTo(y));
        System.out.println("apple vs banana  : " + "apple".compareTo("banana"));
        System.out.println("banana vs apple  : " + "banana".compareTo("apple"));
        System.out.println("same text        : " + "java".compareTo("java"));

        String input = null;
        System.out.println("safe check       : " + "java".equals(input));
    }
}
🖥️ Output:
equals : false
equalsIgnoreCase : true
compareTo : 32
apple vs banana : -1
banana vs apple : 1
same text : 0
safe check : false
  • equals is case-sensitive. Use equalsIgnoreCase to ignore capitals.
  • compareTo gives 0 for equal text, a negative number if the first comes earlier in dictionary order, and a positive number if later. Here “apple” and “Apple” differ by 32, the gap between the codes of ‘a’ (97) and ‘A’ (65).
  • Put the known String first, as in "java".equals(input). If input is null, this simply returns false instead of crashing.

4️⃣ Strings Are Immutable

s = "Hello"
object A: “Hello”
s.concat(” World”)
new object B
“Hello World”
Object A is never changed. Unless you write s = s.concat(...), the new object B is thrown away. This is immutability.

Figure 4: Strings are immutable: operations create new Strings.

public class Immutable {
    public static void main(String[] args) {
        String s = "Hello";
        s.concat(" World");
        System.out.println("after concat (ignored): " + s);

        s = s.concat(" World");
        System.out.println("after assigning       : " + s);

        String t = "java";
        String u = t.toUpperCase();
        System.out.println(t + " -> " + u);

        String original = "abc";
        String alias = original;
        original = original + "d";
        System.out.println("original = " + original + ", alias = " + alias);
    }
}
🖥️ Output:
after concat (ignored): Hello
after assigning : Hello World
java -> JAVA
original = abcd, alias = abc
  • Every method that “changes” a String really returns a new String. The original stays as it was.
  • If you ignore the result, nothing happens. Always store it: s = s.concat(...).
  • Because Strings never change, it is safe to share them, which is why the pool is possible. The alias still holds “abc” after original is changed.
  • Joining many Strings inside a long loop creates many temporary objects. For that job use StringBuilder (Lesson 24).

5️⃣ Concatenation and Text Blocks

public class Concat {
    public static void main(String[] args) {
        int a = 3, b = 4;
        System.out.println("Sum: " + a + b);
        System.out.println("Sum: " + (a + b));
        System.out.println(a + b + " is the sum");
        String s = "Roll" + " " + 21045;
        System.out.println(s);
        String multi = """
            Dear student,
              Welcome to Java.
            """;
        System.out.print(multi);
    }
}
🖥️ Output:
Sum: 34
Sum: 7
7 is the sum
Roll 21045
Dear student,
Welcome to Java.
  • + works left to right (Lesson 15). In "Sum: " + a + b, the text comes first, so 3 and 4 are joined as text and give “34”. Brackets fix it: "Sum: " + (a + b).
  • In a + b + " is the sum" the numbers are added first because no String has appeared yet.
  • A text block (""" … """, Java 15 and later) lets you write several lines without \n. Java removes the common indentation.

6️⃣ Errors Beginners Meet

NullPointerException: calling a method on null

public class Npe {
    public static void main(String[] args) {
        String s = null;
        System.out.println(s.length());
    }
}
🖥️ Runtime error:
Exception in thread “main” java.lang.NullPointerException: Cannot invoke “String.length()” because “<local1>” is null
at Npe.main(Npe.java:4)
  • s points to nothing, so s.length() has no object to work on. Check if (s != null) first. (The message shows <local1> because the program was compiled without debug names; an IDE shows s.)

Index beyond the String

public class Sioobe {
    public static void main(String[] args) {
        String t = "Java";
        System.out.println(t.charAt(10));
    }
}
🖥️ Runtime error (trimmed):
Exception in thread “main” java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 4
at java.base/jdk.internal.util.Preconditions$1.apply(Preconditions.java:55)
… (several internal lines)
at java.base/java.lang.String.charAt(String.java:1544)
at Sioobe.main(Sioobe.java:4)
  • “Java” has indexes 0 to 3. Read the first line for the cause, and the last line starting with your own class name for where it happened.

Mixing up quotes and types

public class Bad4 {
    public static void main(String[] args) {
        char c = "A";
        int n = "5";
        String s = 5;
    }
}
🖥️ Compiler message:
Bad4.java:3: error: incompatible types: String cannot be converted to char
char c = “A”;
^
Bad4.java:4: error: incompatible types: String cannot be converted to int
int n = “5”;
^
Bad4.java:5: error: incompatible types: int cannot be converted to String
String s = 5;
^
3 errors
  • Double quotes make a String, and single quotes make a char. Use Integer.parseInt("5") and String.valueOf(5) to convert (Lesson 9).

⚠️ Common Mistakes

MistakeProblemFix
s1 == s2 to compare textCompares referencess1.equals(s2)
s.toUpperCase(); without storingStrings are immutables = s.toUpperCase();
input.equals("yes") when input may be nullNullPointerException"yes".equals(input)
Single quotes for a StringCompile errorUse double quotes
s.length (no brackets)length() is a method for Stringss.length()
Joining text and numbers in the wrong order“Sum: 34” instead of 7Brackets around the arithmetic

❓ Frequently Asked Questions

Q1. Why is String immutable?
It makes Strings safe to share (the pool), safe as keys in collections, and safe in multi-threaded programs.

Q2. What is the difference between “” and null?
"" is a real String with no characters. null means there is no String at all.

Q3. How many objects does new String(“java”) create?
One on the heap, plus the pooled literal "java" if it was not already there.

Q4. Is String a keyword?
No. It is a class in java.lang, which Java imports automatically.

✅ Key Takeaways

  • A String is an object holding text, written in double quotes, indexed from 0.
  • String literals are shared through the string pool. new String(...) makes a separate object.
  • Compare text with equals() (or equalsIgnoreCase). == compares references.
  • Strings are immutable: methods return new Strings, so store the result.
  • "text".equals(x) is safe against null.
🎓 Practice questions: (1) Explain why "java" == "java" is true but new String("java") == "java" is false. (2) Write a program that checks whether a String is a palindrome. (3) What does "Hi" + 1 + 2 print, and 1 + 2 + "Hi"? (4) Why does s.toUpperCase(); alone do nothing? (5) How would you safely compare a user’s input with “exit” when the input might be null?
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision