Java Strings — Immutable Strings, Methods, StringBuilder
Learning Objectives
- Explain what makes String objects immutable
- Call common String methods for inspection and transformation
- Compare string content correctly with equals
- Use StringBuilder for efficient repeated concatenation
Overview
Text is everywhere in software: names, messages, file paths, JSON payloads. In Java, text lives in the String class. A String object stores a sequence of characters and provides many methods that inspect or transform text without making you write loops for every task.
The most important property of String is immutability. Once a String object is created, its contents never change. Methods that appear to change a string actually return a brand new String and leave the original untouched.
Creating Strings
You can create strings with literals or with the new operator, but literal syntax is preferred because Java can reuse cached instances.
String a = "Hello";
String b = new String("Hello");
String c = a + " World";
System.out.println(a);
System.out.println(c);
System.out.println(a.length());
The plus operator concatenates strings. When either side of plus is a String, the other side is converted to text automatically.
Why Immutability Matters
Immutability brings three practical benefits. String objects are safe to share between threads because nobody can change them. Their content can be cached by the JVM for quick reuse. The value of a hash code never changes, which keeps String reliable as a key in maps you will meet later.
The tradeoff is that repeated concatenation in a loop creates many temporary objects. That is the problem StringBuilder solves.
Essential String Methods
The table below lists methods you will use constantly. All of them return a result and leave the original string unchanged.
| Method | Purpose | Example result |
|---|---|---|
| length | Count of characters | Java has 4 |
| charAt | Character at an index | J from Java |
| toUpperCase | Whole text to upper case | HELLO |
| toLowerCase | Whole text to lower case | hello |
| trim | Remove leading and trailing spaces | trimmed text |
| contains | Check for a substring | true or false |
| indexOf | First position of a match or negative one | 2 |
| replace | Replace every matching character | Hanoj style swaps |
| substring | Slice between indexes | part of text |
| isEmpty | True when length is zero | true or false |
String email = " [email protected] ";
String clean = email.trim().toLowerCase();
System.out.println(clean);
System.out.println(clean.contains("@"));
System.out.println(clean.indexOf("@"));
System.out.println(clean.substring(0, 3));
Method chaining works because each call returns a new String that the next call can use.
equals versus Double Equals
Double equals on objects compares references, meaning whether two variables point at the exact same object in memory. String content comparison needs the equals method. Ignoring this rule is one of the most common beginner bugs.
String first = "java";
String second = new String("java");
System.out.println(first == second); // false, different objects
System.out.println(first.equals(second)); // true, same characters
System.out.println(first.equalsIgnoreCase("JAVA")); // true
Always use equals for text content and equalsIgnoreCase when capitalization should not matter.
Mutating Text with StringBuilder
StringBuilder is a mutable text buffer. It can append, insert, delete, and reverse without allocating a new object for every step. Build strings in loops with StringBuilder, then convert once to String at the end.
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append("Item ").append(i).append("; ");
}
sb.deleteCharAt(sb.length() - 1);
sb.reverse();
String result = sb.toString();
System.out.println(result);
StringBuilder also supports chaining because each mutator returns the same builder instance. It is not synchronized, which makes it faster for single-threaded work. A related class, StringBuffer, offers thread safety at a small performance cost.
Common Patterns
Splitting text uses the split method and produces an array of parts. Joining parts uses String.join. Parsing numbers out of text pairs with the parse methods from the type casting lesson. Each pattern replaces what would otherwise be a hand written loop.
String csv = "red,green,blue";
String[] colors = csv.split(",");
String joined = String.join(" | ", colors);
System.out.println(colors.length);
System.out.println(joined);
Key Takeaways
💡
- String objects are immutable; transformations return new instances
- Use equals and equalsIgnoreCase for content, never double equals alone
- Chain inspection methods such as trim, toLowerCase, and contains cleanly
- StringBuilder is the right tool for building text in loops
- split and join handle common parsing and formatting tasks
Practice Questions
- Write code that trims a user input string, converts it to lower case, and checks whether it contains the word java.
- Why does comparing two identical string literals with double equals often work while comparing new String objects with double equals fails?
- Build the text one two three using StringBuilder in a loop, then print it as a String.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions