Chapter 07
Java Strings
4 topics · 1 sections · beginner-friendly study notes · Updated
A String in Java is an immutable sequence of characters stored as an object.
This chapter covers creating strings, the most-used String methods, the mutable StringBuffer and StringBuilder classes, and the String constant pool that decides when == is true.
Strings appear in almost every Java program, and questions on immutability, == vs equals and the string pool are asked in nearly every interview.
Reading user input, building SQL and JSON text, validating emails, log messages, file names and URLs.
String in Java
String is a final class in java.lang that represents an immutable sequence of characters. A String object can be created with a literal (String s = "Java";) or with the new keyword (new String("Java")). Once created, its contents can never change.
In short: A String is a piece of text that is locked after it is written. Every change creates a brand-new piece of text.
Think about it
Text handling is needed everywhere. Immutability makes strings safe, cacheable and secure (for example for file paths, class names and network connections). A printed certificate: you cannot edit the printed words; to change a word you print a new certificate.
Internally a String holds a char/byte array that is private and final, and the class itself is final, so nobody can subclass it and break immutability.
Because of this, Strings are thread-safe, safe to use as HashMap keys (the hash code can be cached) and safe to share through the string pool.
Methods such as concat, replace, toUpperCase and substring do NOT change the original; they return a new String, so you must store the result.
The == operator compares references (are both variables pointing to the same object?
) while equals() compares the characters.
Always compare text with equals().
To avoid NullPointerException use `"literal".
equals(variable)`.
Strings implement Comparable, CharSequence and Serializable.
Concatenation with + creates new objects; inside a loop prefer StringBuilder.
Key points
- Immutable: Object state cannot change after creation.
- String literal: Text in double quotes; stored in the string pool.
equals(): Compares the character content of two strings.==: Compares whether two references point to the same object.compareTo(): Lexicographic comparison; returns negative, zero or positive.- String is final, immutable and implements Comparable<String>, CharSequence, Serializable.
- Two ways to create: literal (pool) and new (heap, always a new object).
- Never use
==to compare string content; useequals()orequalsIgnoreCase(). concat()and + create a new string; the original is untouched.
Example
CodeCreating strings, immutability and equals vs ==:
public class StringBasics {
public static void main(String[] args) {
String a = "Java";
String b = "Java";
String c = new String("Java");
System.out.println(a == b); // true (same pooled object)
System.out.println(a == c); // false (c is a new heap object)
System.out.println(a.equals(c)); // true (same characters)
String s = "Hello";
s.concat(" World"); // result is thrown away
System.out.println(s); // Hello
s = s.concat(" World"); // store the new String
System.out.println(s); // Hello World
System.out.println("apple".compareTo("banana")); // -1 ('a' - 'b')
System.out.println("Java".equalsIgnoreCase("JAVA")); // true
String name = null;
System.out.println("admin".equals(name)); // false, no NullPointerException
System.out.println(name + "!"); // null!
}
}String Methods in Java
String methods are the built-in operations of the String class used to inspect, search, extract, compare, convert and split text, for example length(), charAt(), substring(), indexOf(), contains(), replace(), split(), trim() and toUpperCase().
In short: Methods are the toolbox for text. Each tool gives you an answer or a new string; the original string never changes.
Think about it
Most string programs (palindrome, reverse, count vowels, anagram, validate) are built entirely from these methods. Cleaning a form field: trim the spaces, convert to lower case, split the full name into first and last name.
Indexing starts at 0 and the last valid index is length()-1; charAt with a bad index throws StringIndexOutOfBoundsException.
substring(begin, end) includes begin and excludes end.
indexOf returns -1 when nothing is found.
trim() removes leading/trailing spaces (<= U+0020); strip() (Java 11) is Unicode-aware; isBlank() is true for empty or whitespace-only text.
split(regex) takes a regular expression, so special characters such as ".
" and "|" must be escaped ("\\.
" in source).
`String.
join(delim, items)` is the reverse of split.
valueOf converts primitives to String, toCharArray() gives a char[] (handy for sorting characters), and `String.
format / formatted` build text using %d, %s, %.
2f.
repeat(n) (Java 11) repeats a string.
Since every method returns a new String, calls can be chained.
Key points
Example
CodeFrequently used String methods:
import java.util.Arrays;
public class StringMethodsDemo {
public static void main(String[] args) {
String s = " Hello Java World ";
String t = s.trim(); // "Hello Java World"
System.out.println(t.length()); // 16
System.out.println(t.charAt(4)); // o
System.out.println(t.substring(6, 10)); // Java
System.out.println(t.indexOf("a")); // 7
System.out.println(t.lastIndexOf("a")); // 9
System.out.println(t.indexOf("xyz")); // -1
System.out.println(t.contains("Java")); // true
System.out.println(t.toUpperCase()); // HELLO JAVA WORLD
System.out.println(t.replace('l', 'L')); // HeLLo Java WorLd
String[] parts = t.split(" ");
System.out.println(Arrays.toString(parts)); // [Hello, Java, World]
System.out.println(String.join("-", parts)); // Hello-Java-World
System.out.println(" ".isBlank()); // true
System.out.println("Hi".repeat(3)); // HiHiHi
System.out.println(String.format("%05d|%.2f|%s", 42, 3.14159, "ok")); // 00042|3.14|ok
// Palindrome check using only String methods
String w = "madam";
String rev = new StringBuilder(w).reverse().toString();
System.out.println(w.equals(rev)); // true
// Count vowels
int vowels = 0;
for (char ch : "education".toCharArray()) {
if ("aeiou".indexOf(ch) != -1) vowels++;
}
System.out.println(vowels); // 5
}
}Inspect
length(), isEmpty(), isBlank(), charAt(i), startsWith(), endsWith(), contains().
Search
indexOf(), lastIndexOf() return the position or -1.
Extract and change
substring(), replace(), trim(), strip(), toUpperCase(), toLowerCase(), repeat().
Split and join
split(regex) gives String[]; String.
join(delim, parts) rebuilds text.
Convert
toCharArray(), String.
valueOf(x), String.
format(), Integer.
parseInt(s).
StringBuffer vs StringBuilder
StringBuffer and StringBuilder are mutable sequences of characters in java.lang. StringBuffer is thread-safe (its methods are synchronized) and slower; StringBuilder (Java 5) has the same API but is not synchronized, so it is faster in single-threaded code.
In short: String is a printed page. StringBuilder is a whiteboard you can edit quickly. StringBuffer is the same whiteboard but with a lock on the door.
Think about it
Building large text with + inside loops wastes memory and time. Knowing the three classes is a guaranteed interview question. Generating a report with thousands of lines, or building a SQL query piece by piece.
Both keep a resizable char buffer.
The default capacity is 16; new StringBuilder("abc") has capacity 16 + 3 = 19.
When the buffer is full it grows to (oldCapacity × 2) + 2.
append, insert, delete, deleteCharAt, replace, reverse and setCharAt change the SAME object and return this, which allows chaining.
Neither class overrides equals() or hashCode(), so `sb1.
equals(sb2)` is false even for equal text; compare with `sb1.
toString().
equals(sb2.
toString())`.
Repeated s += x in a loop creates a new String every time, which is O(n²); a StringBuilder makes it O(n).
Rule of thumb: use String for constants, StringBuilder for local text building, StringBuffer only when several threads share one buffer (and even then, external locking is often cleaner).
Key points
- Mutable: Can be modified in place.
- Synchronized: Only one thread can run the method at a time.
- Capacity: Size of the internal buffer (not the same as length).
- Method chaining: Calling several methods in a row because each returns the same object.
- String: immutable, thread-safe, uses string pool.
- StringBuffer: mutable, thread-safe, slower, since JDK 1.0.
- StringBuilder: mutable, NOT thread-safe, faster, since JDK 1.5.
- No equals() override in either; use toString() or compareTo() (Java 11).
Example
CodeMutable text with StringBuilder and StringBuffer:
public class BuilderDemo {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
System.out.println(sb.capacity()); // 16
System.out.println(new StringBuilder("abc").capacity()); // 19
sb.append("Hello").append(' ').append("World"); // chaining
System.out.println(sb); // Hello World
sb.insert(0, ">>");
System.out.println(sb); // >>Hello World
sb.deleteCharAt(0).deleteCharAt(0);
sb.setCharAt(0, 'J');
System.out.println(sb); // Jello World
sb.replace(0, 5, "Hi");
System.out.println(sb); // Hi World
System.out.println(sb.reverse()); // dlroW iH
System.out.println(sb.length()); // 8
StringBuilder x = new StringBuilder("same");
StringBuilder y = new StringBuilder("same");
System.out.println(x.equals(y)); // false
System.out.println(x.toString().equals(y.toString())); // true
// Speed comparison idea: concatenation in a loop
String slow = "";
for (int i = 0; i < 5; i++) slow += i; // 5 temporary Strings
StringBuilder fast = new StringBuilder();
for (int i = 0; i < 5; i++) fast.append(i); // one buffer
System.out.println(slow + " " + fast); // 01234 01234
StringBuffer safe = new StringBuffer("log");
safe.append(":ready"); // synchronized methods
System.out.println(safe); // log:ready
}
}String Pool in Java
The String pool (string constant pool / intern pool) is a special area of the heap where the JVM stores unique string literals so that identical literals share one object. `String.intern()` returns the pooled instance for a given string.
In short: The JVM keeps one copy of every literal text. If you write "Java" ten times, all ten variables point to the same object.
Think about it
The pool explains the classic output-prediction questions and shows why immutability is required: shared objects must never change. A shared library book: many students borrow the same copy rather than printing a copy each.
When the compiler sees a literal, the JVM looks in the pool: if an equal string exists it reuses it, otherwise it adds it.
So "Java" == "Java" is true.
`new String("Java")` always creates a new object on the heap (and the literal "Java" is also placed in the pool if not present), which is why `new String("Java") == "Java"` is false.
Since Java 7 the pool lives in the heap (earlier it was in PermGen) so unused pooled strings can be garbage collected.
Compile-time constants are folded: "Ja" + "va" becomes the literal "Java" and equals the pooled one, and so does `final String f = "Ja"; f + "va"`.
But a non-final variable y + "va" is computed at runtime and creates a new heap object.
Calling intern() on such a string returns the pooled copy.
The pool saves memory and makes literal comparison fast, but never rely on == for content.
Key points
- String constant pool: Heap area holding unique literal strings.
intern(): Returns the canonical pooled string equal to this one.- Compile-time constant: Expression made of literals/final constants that the compiler evaluates.
- Heap object: Object created with new, stored outside the pool.
- Literal: pool. new String("x"): heap object (plus pooled literal x).
- new String("Java") creates up to 2 objects; a literal creates at most 1.
- Since Java 7 the pool is part of the heap, not PermGen.
- Use
intern()only for rare memory-saving cases.
Example
CodeString pool, new and intern():
public class PoolDemo {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Java";
String s3 = new String("Java");
String s4 = s3.intern();
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s1 == s4); // true (intern returns pooled copy)
System.out.println("Ja" + "va" == s1); // true (constant folding)
final String f = "Ja";
System.out.println(f + "va" == s1); // true (f is a constant)
String y = "Ja";
String z = y + "va"; // computed at run time
System.out.println(z == s1); // false
System.out.println(z.intern() == s1); // true
System.out.println(z.equals(s1)); // true
}
}Solved examples
Predict the output: String a = "hi"; String b = new String("hi"); System.out.println((a == b) + " " + a.equals(b));
Two booleans
Formula Applied:—Approach note: Literal vs new is the favourite trick in output questions.
Count the vowels in "Programming" using String methods.
Number of vowels
Formula Applied:—Approach note: indexOf on a constant vowel string is shorter than five comparisons.
What does this print? String s = "abc"; s.toUpperCase(); s.concat("d"); System.out.println(s);
Printed text
Formula Applied:—Approach note: If you do not assign the returned String, nothing is saved.
Reverse the words of "java is fun" to get "fun is java".
Reversed sentence
Formula Applied:—Approach note: Reversing characters (sb.reverse()) is different from reversing word order.
Real-world applications
Using Java Strings in real projects
Reading user input, building SQL and JSON text, validating emails, log messages, file names and URLs.
Common mistakes
❌ Myth: s.toUpperCase() changes the string s.
Why this is wrong: Strings are immutable, so the method returns a new String.
✅ Verified Truth: Assign the result: s = s.toUpperCase().
⚠️ Exam Tip: Immutability output questions appear in every Java paper.
❌ Myth: == and equals() are the same for strings.
Why this is wrong: == compares references, equals() compares content.
✅ Verified Truth: Use equals() for content; == only for reference identity.
⚠️ Exam Tip: Literal == literal is true, new String == literal is false.
❌ Myth: StringBuilder is thread-safe.
Why this is wrong: Only StringBuffer has synchronized methods.
✅ Verified Truth: Use StringBuffer or external locking for shared buffers.
⚠️ Exam Tip: Remember: Builder = faster, Buffer = safer.
❌ Myth: new String("a") creates exactly one object.
Why this is wrong: The literal "a" may also be created in the pool.
✅ Verified Truth: It can create two objects: one in the pool, one on the heap.
⚠️ Exam Tip: Classic interview question: how many objects are created?
Revision notes
A String in Java is an immutable sequence of characters stored as an object. This chapter covers creating strings, the most-used String methods, the mutable StringBuffer and StringBuilder classes, and the String constant pool that decides when == is true.
High-Yield Quick Revision Points
- String is final and immutable; methods return new strings
- Use equals() for content; == compares references
- substring(begin, end) excludes end; indexOf returns -1 when absent
- StringBuilder: fast, not thread-safe. StringBuffer: synchronized
- Literals share one pooled object; new String always creates a new one
- intern() returns the pooled string
Practice questions
Which class is immutable?
What is the output of "Java".substring(1, 3)?
What does "abc".compareTo("abd") return?
Which is faster in single-threaded code?
What is the default capacity of new StringBuilder()?
Where are string literals stored?