Chapter 9: Strings
1. What is a String in Java? (The Basics)
A String is a sequence of characters (text). In Java, String is a class (not a primitive type like int or char).
|
0 1 2 3 4 5 6 7 |
String name = "Webliance"; // most common way String greeting = new String("नमस्ते"); // also valid, but rarely used |
Important facts:
- Strings are objects (reference type)
- They live in a special memory area called String Pool (more on this soon)
- Strings are immutable — once created, you cannot change their content
Real-life analogy: Think of a String as a written note on a piece of paper. You can read it, copy it, show it to others, but you cannot erase or change any letter on the original paper. If you want a different message, you write a new note.
2. String Immutability – Why It’s a Big Deal
Immutability means: Once a String object is created, its value cannot be changed.
Example:
|
0 1 2 3 4 5 6 7 8 9 |
String s = "Hello"; s = s + " World"; // This does NOT change the original "Hello" // It creates a NEW String "Hello World" // The old "Hello" still exists in memory (until GC) |
Why immutable? (Benefits)
- Thread-safe — safe to share between threads
- Security — passwords, URLs, file paths can’t be accidentally modified
- String Pool efficiency — same literal strings share the same object
- Hashcode caching — hashCode() never changes → good for HashMap keys
String Pool (Special Memory Area):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
String a = "Mumbai"; String b = "Mumbai"; String c = new String("Mumbai"); System.out.println(a == b); // true (same object in pool) System.out.println(a == c); // false (different object) System.out.println(a.equals(c)); // true (same content) |
Never compare Strings with == — always use .equals()!
3. Important String Methods (The Most Used Ones)
Here’s a table of the most important methods you’ll use every day:
| Method | What it does | Example | Result |
|---|---|---|---|
| length() | Number of characters | “Hello”.length() | 5 |
| charAt(index) | Character at position | “Hello”.charAt(1) | ‘e’ |
| substring(begin) | From index to end | “Hello World”.substring(6) | “World” |
| substring(begin, end) | From begin (inclusive) to end (exclusive) | “Hello World”.substring(0, 5) | “Hello” |
| toUpperCase() / toLowerCase() | Convert case | “Webliance”.toUpperCase() | “WEBLIANCE” |
| trim() | Remove leading/trailing whitespace | ” Hello “.trim() | “Hello” |
| replace(old, new) | Replace all occurrences | “Hello”.replace(“l”, “p”) | “Heppo” |
| contains(substring) | Check if contains | “Java is fun”.contains(“fun”) | true |
| startsWith() / endsWith() | Check prefix/suffix | “Mumbai”.startsWith(“Mu”) | true |
| indexOf(substring) | First position of substring (-1 if not found) | “Hello World”.indexOf(“World”) | 6 |
| split(regex) | Split into array | “a,b,c”.split(“,”) | [“a”,”b”,”c”] |
| equals() / equalsIgnoreCase() | Compare content | “Hello”.equals(“hello”) | false |
| isEmpty() / isBlank() (Java 11+) | Check if empty or only whitespace | ” “.isBlank() | true |
Complete Example Program — String Methods in Action
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class StringMethodsDemo { public static void main(String[] args) { String text = " Hello, Webliance from Mumbai! "; System.out.println("Original: '" + text + "'"); System.out.println("Length: " + text.length()); // 32 System.out.println("Trimmed: '" + text.trim() + "'"); // Hello, Webliance from Mumbai! System.out.println("Uppercase: " + text.toUpperCase()); System.out.println("Contains 'Mumbai': " + text.contains("Mumbai")); // true System.out.println("Starts with 'Hello': " + text.trim().startsWith("Hello")); // true // Substring String name = text.trim().substring(7, 17); // "Webliance" System.out.println("Extracted name: " + name); // Replace String replaced = text.replace("Mumbai", "India"); System.out.println("Replaced: " + replaced.trim()); // Split String[] words = text.trim().split(" "); System.out.println("Words:"); for (String word : words) { System.out.println("→ " + word); } // indexOf System.out.println("Position of 'from': " + text.indexOf("from")); // 19 } } |
4. String Concatenation – The Right & Wrong Way
Wrong way (slow & memory heavy):
|
0 1 2 3 4 5 6 7 8 9 |
String result = ""; for (int i = 0; i < 10000; i++) { result += i + " "; // Creates 10,000 new Strings! } |
Right way — Use StringBuilder or StringBuffer
5. StringBuilder vs StringBuffer (Mutable Strings)
Both are mutable versions of String — you can change them without creating new objects.
| Feature | StringBuilder | StringBuffer |
|---|---|---|
| Mutable? | Yes | Yes |
| Thread-safe? | No (faster) | Yes (synchronized) |
| Best for | Single-threaded code (99% cases) | Multi-threaded code |
| Speed | Faster | Slightly slower |
Common methods (same for both):
- append() – add to end
- insert()
- delete()
- reverse()
- toString() – convert back to String
Example: Efficient Concatenation
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class StringBuilderDemo { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("Hello"); sb.append(", "); sb.append("Webliance"); sb.append(" from Mumbai!"); sb.insert(7, " dear"); // insert at position 7 System.out.println(sb.toString()); // Hello, dear Webliance from Mumbai! sb.reverse(); System.out.println("Reversed: " + sb); sb.delete(0, 7); // remove first 7 chars System.out.println("After delete: " + sb); } } |
Real-world tip: Always use StringBuilder when building strings in loops or dynamically.
6. Quick Recap Table (Your Cheat Sheet)
| Concept | Key Points / Best Practice |
|---|---|
| Immutability | Strings cannot change → use StringBuilder for changes |
| Comparison | Always .equals() or .equalsIgnoreCase() — never == |
| Concatenation | + is OK for small cases; use StringBuilder for loops |
| String Pool | Literals like “Hello” are shared → saves memory |
| StringBuilder | Fast, not thread-safe → default choice |
| StringBuffer | Thread-safe → use only in multi-threaded code |
| Common methods | length(), substring(), trim(), split(), replace() |
Common Mistakes & Fixes
| Mistake | Problem | Fix |
|---|---|---|
| if (s1 == s2) | Compares references, not content | Use s1.equals(s2) |
| String s = “”; for(…) s += … | Very slow + memory waste | Use StringBuilder |
| new String(“Hello”) instead of literal | Creates extra object outside pool | Just use “Hello” |
| Forgetting trim() on user input | Extra spaces cause bugs | Always input.trim() |
| substring(3, 3) | Empty string | Remember: end index is exclusive |
Homework for You (Practice to Master!)
- Basic: Take user’s full name → print length, uppercase, lowercase, first name, last name.
- Medium: Write a program that checks if a string is palindrome (e.g., “radar”, “नमन”) — use StringBuilder.reverse().
- Advanced: Read a sentence → split into words → reverse the order of words → join back with spaces.
- Fun: Create a program that counts how many times each vowel (a,e,i,o,u) appears in a paragraph.
- Challenge: Build a long sentence using StringBuilder by appending 1000 numbers — compare time with + operator.
You’re doing fantastic! Strings are everywhere in Java — mastering them will make your code cleaner, faster, and more professional.
