Beginner level · Module 3: Arrays, Strings and ArrayList · Lesson 2 of 3
Working with Text: String and StringBuilder
Clean, compare, split and build text with String methods, and know why Strings are immutable.
In this lesson you will
- Use trim, toUpperCase, equalsIgnoreCase, contains, substring and split
- Build long text efficiently with StringBuilder
Key concepts
immutable StringequalsIgnoreCasesplitStringBuilder
The lesson
A String cannot change once created. Methods such as trim() and toUpperCase() return a new String, so you must store the result: name = name.trim();. Forgetting to store the result is a common mistake.
Useful methods include length(), charAt(i), indexOf(text), contains(text), substring(start, end), replace(a, b) and split(","). split turns a line such as "Akol,72" into an array {"Akol", "72"}, which you can convert with Integer.parseInt().
Joining Strings with + inside a loop creates many temporary objects. StringBuilder collects text efficiently: create one, call append() in the loop, and call toString() at the end.
Step by step
- Read a name with extra spaces and mixed case and clean it with trim().
- Compare two names with equalsIgnoreCase().
- Split "Akol,72" into name and mark and convert the mark to an int.
- Build a comma-separated list of names with StringBuilder.
Practice activity
Write a program that reads lines like " mary LADU , 68 " and prints them as "Mary Ladu — 68" in a clean, consistent format.
Expected result: Messy lines are printed with trimmed, correctly capitalised names and the mark as a number.
Check your understanding
-
Why does name.trim(); on its own not change name?
Show answer
Strings are immutable; trim() returns a new String that must be assigned back.
-
What does "a,b,c".split(",") return?
Show answer
An array of three Strings: "a", "b" and "c".
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.