Strings
Strings are the most commonly used type in real-world Java. Every user input, every file name, every database query, every error message — they're all strings. In this lesson, you'll learn to search, compare, split, format, and efficiently build strings. You'll also learn the #1 Java gotcha : why == doesn't work for comparing strings.
Learn Strings in our free Java course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free Java course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn
- ✅ Creating strings and concatenation
- ✅ Immutability — why strings can never be changed
- ✅ The String Pool — how Java saves memory with string reuse
- ✅ Essential methods: length, charAt, substring, indexOf, contains
- ✅ Comparing strings with .equals() vs == (critical!)
- ✅ Transforming: toUpperCase, replace, trim, split, join
- ✅ StringBuilder — efficient string building in loops
- ✅ String.format() — clean formatted output
💡 Real-World Analogy
A String is like a necklace of letter beads . Each bead is a character, and you can examine them, count them, or create a new necklace — but you can never change the beads on an existing necklace . Every "change" actually creates a brand new necklace. This is called immutability .
1️⃣ Creating Strings & Concatenation
You create strings by wrapping text in double quotes. You can combine strings using the + operator (concatenation):
2️⃣ Immutability & The String Pool
Immutability means once a String is created, it can never be changed . Every method that seems to "modify" a string actually creates a brand new string and returns it. The original is untouched.
Java also maintains a String Pool — a special memory area that reuses identical string literals:
🔑 This is why == is unreliable for strings! It compares memory addresses, not content. Two strings can have identical text but be different objects in memory. Always use .equals() .
3️⃣ Essential String Methods
These are the methods you'll use every day. Memorize these and you'll handle 90% of string tasks:
4️⃣ String Comparison — The #1 Java Gotcha
This is the single most common bug Java beginners make. Let's be absolutely clear about it:
🔑 The rule: == checks "are these the exact same object in memory?" .equals() checks "do these contain the same text?" You almost always want .equals() .
5️⃣ StringBuilder — Efficient String Building
Because strings are immutable, concatenation in a loop creates a new string object every iteration . For large loops, this wastes massive amounts of memory. Use StringBuilder instead:
💡 Rule of thumb: If you're concatenating in a loop, use StringBuilder. For a few simple concatenations outside loops, regular + is fine.
6️⃣ String.format() — Clean Formatted Output
Instead of ugly concatenation with lots of + signs, use String.format() for readable, clean string construction:
7️⃣ Real-World String Patterns
Here are patterns you'll use constantly in real Java applications:
Common Mistakes
- ❌ Using == instead of .equals():
- ❌ Forgetting strings are immutable:
- ❌ Calling methods on null: null.length() crashes with NullPointerException . Always check for null first, or use the constant-first pattern: "expected".equals(input) .
- ❌ Concatenation in loops: Creates thousands of temporary objects. Use StringBuilder instead.
- ❌ Confusing length vs length(): Arrays: arr.length (property). Strings: str.length() (method with parentheses).
Pro Tips
💡 Use .equalsIgnoreCase() for user input — users might type "YES", "Yes", or "yes".
💡 Use .strip() instead of .trim() (Java 11+) — it handles Unicode whitespace properly.
💡 Use String.format() for readable string construction instead of chaining + operators.
💡 Java 15+ text blocks: Use """multi-line text""" for SQL queries, HTML, and JSON.
💡 String.join() is your friend: String.join(", ", list) is cleaner than manual loops.
📋 Quick Reference
Method
Example
Result
length()
"Hello".length()
5
charAt(i)
"Hello".charAt(1)
'e'
equals()
"Hi".equals("Hi")
true
substring(a,b)
"Hello".substring(0,3)
"Hel"
indexOf()
"Hello".indexOf("ll")
2
split()
"a,b".split(",")
["a","b"]
replace()
"Hi".replace("H","B")
"Bi"
trim()
" Hi ".trim()
"Hi"
format()
String.format("%s=%d","x",5)
"x=5"
🎉 Lesson Complete!
You now know how to create, compare, search, split, format, and efficiently build strings in Java! Strings appear in virtually every Java program — from parsing user input to building SQL queries to formatting log messages.
Next up: Object-Oriented Programming — learn to design classes and objects, the foundation of all Java applications.
Practice quiz
What does it mean that Strings are immutable?
- They can be changed in place
- They are always empty
- Once created, a String can never be changed
- They cannot be printed
Answer: Once created, a String can never be changed. Immutable means a String never changes; methods like toUpperCase return a brand-new String.
Which is the correct way to compare two Strings' text content?
- s1.equals(s2)
- s1 == s2
- s1 = s2
- s1.compare(s2)
Answer: s1.equals(s2). Use .equals() to compare content; == compares object references.
What does "Hello, World!".length() return?
- 12
- 11
- 14
- 13
Answer: 13. Counting all characters including the comma, space, and !, the length is 13.
What does "Hello, World!".substring(7) return?
- "World"
- "World!"
- ", World!"
- "Hello, "
Answer: "World!". substring(7) returns everything from index 7 to the end: "World!".
What does name.toUpperCase(); do if you do NOT assign the result?
- Nothing useful — the new String is discarded
- Changes name in place
- Throws an error
- Returns null
Answer: Nothing useful — the new String is discarded. Strings are immutable, so the new uppercase String is thrown away unless you store it.
What does System.out.println("Score: " + 5 + 3); print?
- Score: 8
- Score: 5 3
- Score: 53
- 8
Answer: Score: 53. Left-to-right, "Score: " + 5 makes a String, then + 3 appends '3', giving "Score: 53".
Why use StringBuilder instead of += inside a large loop?
- It is the only way to concatenate
- += creates a new String each iteration, wasting memory
- StringBuilder is immutable
- It sorts the text
Answer: += creates a new String each iteration, wasting memory. Because Strings are immutable, += makes a new object every iteration; StringBuilder uses one mutable buffer.
What does "yes".equals(input) return when input is null?
- true
- It throws NullPointerException
- null
- false (no crash)
Answer: false (no crash). Putting the constant first is null-safe: it returns false instead of throwing NullPointerException.
What does "Hello".indexOf("ll") return?
- 1
- 2
- 3
- -1
Answer: 2. "ll" starts at index 2 in "Hello".
Which format specifier prints a floating-point number to 2 decimal places?
- %d
- %s
- %.2f
- %n
Answer: %.2f. %.2f formats a floating-point value with two decimal places.
Continue this course
- Previous: Previous Lesson
- Next: Next Lesson