đź§µ Working with Strings: The Art of String Manipulation
Imagine you have a magical piece of clay that can become anything you want. Strings in Java are like that clay—you can stretch them, cut them, join them, and shape them into exactly what you need!
🎬 The Story Begins
Meet Maya, a young chef who loves making sandwiches. She doesn’t just throw ingredients together—she carefully modifies, transforms, splits, and joins them to create the perfect meal.
In Java, we do the same with text! Let’s learn how Maya (and you) can become a master of String Manipulation.
đź”§ String Modification Methods
Trimming the Edges
Maya always cuts the crusts off bread. In Java, we trim extra spaces from strings!
String messy = " hello world ";
String clean = messy.trim();
// Result: "hello world"
What happened? The trim() method removed all the spaces from the beginning and end—like cutting off bread crusts!
Replacing Parts
Maya sometimes swaps cheese for lettuce. We can replace parts of strings too:
String sandwich = "cheese and cheese";
String healthy = sandwich.replace("cheese", "lettuce");
// Result: "lettuce and lettuce"
Extracting a Piece (Substring)
Want just a bite? Use substring():
String word = "HAMBURGER";
String piece = word.substring(0, 3);
// Result: "HAM"
Think of it like cutting a slice from position 0 to 3!
🔤 String Case Conversion
Shouting vs Whispering
- UPPERCASE = SHOUTING! 📢
- lowercase = whispering… 🤫
String normal = "Hello World";
String loud = normal.toUpperCase();
// Result: "HELLO WORLD"
String quiet = normal.toLowerCase();
// Result: "hello world"
Real Life Use: Comparing usernames without caring about case:
String input = "JohnDoe";
String stored = "johndoe";
if (input.toLowerCase().equals(stored)) {
System.out.println("Match found!");
}
✂️ String Splitting and Joining
Splitting: Breaking Apart
Maya cuts a long sandwich into slices. We split strings into arrays!
String fruits = "apple,banana,cherry";
String[] pieces = fruits.split(",");
// Result: ["apple", "banana", "cherry"]
The , is our knife—it tells Java where to cut.
Joining: Putting Together
Now let’s make a fruit salad by joining pieces:
String[] fruits = {"apple", "banana", "cherry"};
String salad = String.join(" + ", fruits);
// Result: "apple + banana + cherry"
graph TD A["apple,banana,cherry"] -->|split by comma| B["apple"] A --> C["banana"] A --> D["cherry"] B -->|join with +| E["apple + banana + cherry"] C --> E D --> E
📝 String Formatting
Making Strings Pretty
Imagine filling out a form with blanks:
“Hello, my name is _____ and I am _____ years old.”
In Java, we use String.format():
String name = "Maya";
int age = 10;
String intro = String.format(
"Hello, my name is %s and I am %d years old.",
name, age
);
// Result: "Hello, my name is Maya and I am 10 years old."
Format Codes Cheat Sheet
| Code | Meaning | Example |
|---|---|---|
%s |
String (text) | “Maya” |
%d |
Integer (whole number) | 10 |
%f |
Decimal number | 3.14 |
%.2f |
Decimal with 2 places | 3.14 |
double price = 19.99;
String tag = String.format("Price: $%.2f", price);
// Result: "Price: $19.99"
🏗️ StringBuilder: The Speed Builder
The Problem with Regular Strings
Every time you add to a String, Java creates a brand new string. It’s like writing a letter, then rewriting the WHOLE letter just to add one word!
// SLOW way (creates many strings)
String result = "";
result = result + "Hello";
result = result + " ";
result = result + "World";
The Solution: StringBuilder
StringBuilder is like a magic notebook—you just add to it without rewriting everything!
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
String result = sb.toString();
// Result: "Hello World"
More StringBuilder Tricks
StringBuilder sb = new StringBuilder("Hello World");
// Insert at position 6
sb.insert(6, "Beautiful ");
// Result: "Hello Beautiful World"
// Delete from position 6 to 16
sb.delete(6, 16);
// Result: "Hello World"
// Reverse everything
sb.reverse();
// Result: "dlroW olleH"
graph TD A["StringBuilder Created"] --> B["append Hello"] B --> C["append Space"] C --> D["append World"] D --> E["toString"] E --> F["Hello World"]
When to Use StringBuilder?
| Situation | Use |
|---|---|
| Building text in a loop | âś… StringBuilder |
| Joining 2-3 strings once | Regular String is fine |
| Changing text frequently | âś… StringBuilder |
đź“„ Text Blocks: Beautiful Multi-Line Strings
The Old Way (Messy!)
Writing multi-line text used to be painful:
String html = "<html>\n" +
" <body>\n" +
" <p>Hello!</p>\n" +
" </body>\n" +
"</html>";
All those \n and + signs? Yuck! 🤮
The New Way: Text Blocks (Java 15+)
Text Blocks let you write text exactly as it looks:
String html = """
<html>
<body>
<p>Hello!</p>
</body>
</html>
""";
Magic! ✨ What you see is what you get!
Text Block Rules
- Start with
"""and a new line - Write your text naturally
- End with
"""
String poem = """
Roses are red,
Violets are blue,
Java is awesome,
And so are you!
""";
Text Blocks Keep Formatting
Perfect for:
- HTML templates
- JSON data
- SQL queries
- Poems and stories! đź“–
String json = """
{
"name": "Maya",
"age": 10,
"loves": "coding"
}
""";
🎯 Quick Summary
| Method | What It Does | Example |
|---|---|---|
trim() |
Remove edge spaces | " hi ".trim() → "hi" |
replace() |
Swap parts | "abc".replace("a","x") → "xbc" |
substring() |
Extract piece | "hello".substring(0,2) → "he" |
toUpperCase() |
ALL CAPS | "hi".toUpperCase() → "HI" |
toLowerCase() |
all small | "HI".toLowerCase() → "hi" |
split() |
Break into array | "a,b".split(",") → ["a","b"] |
String.join() |
Array to string | join("-", arr) → "a-b" |
String.format() |
Fill in blanks | format("Hi %s", "Maya") |
StringBuilder |
Fast building | sb.append("text") |
Text Blocks |
Multi-line text | """text""" |
🚀 You Did It!
You just learned how to:
âś… Trim and clean strings âś… Replace parts of text âś… Convert between UPPERCASE and lowercase âś… Split strings into pieces âś… Join pieces back together âś… Format strings with placeholders âś… Use StringBuilder for speed âś… Write beautiful Text Blocks
Maya the chef is proud of you! Now go create something amazing with your new String manipulation skills! 🎉
