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).

Java

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:

Java

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):

Java

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

Java

4. String Concatenation – The Right & Wrong Way

Wrong way (slow & memory heavy):

Java

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

Java

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!)

  1. Basic: Take user’s full name → print length, uppercase, lowercase, first name, last name.
  2. Medium: Write a program that checks if a string is palindrome (e.g., “radar”, “नमन”) — use StringBuilder.reverse().
  3. Advanced: Read a sentence → split into words → reverse the order of words → join back with spaces.
  4. Fun: Create a program that counts how many times each vowel (a,e,i,o,u) appears in a paragraph.
  5. 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.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *