Strings and Their Methods
Every Brew Bar cup has a name written on it, and the till prints it in capitals, checks whether an order says "oat", and compares names to find repeat customers. All of that is work on String values. Strings come with many handy methods, and one rule explains nearly every surprise they cause.
The rule
A String never changes; every method hands you a new one.
Strings are immutable. A method such as toUpperCase() does not alter the original; it returns a fresh string, which you must store if you want to keep it:
String name = "asha";
name.toUpperCase(); // result thrown away
System.out.println(name); // asha
name = name.toUpperCase(); // keep the new string
System.out.println(name); // ASHAThe methods you will reach for most:
| Method | "oat latte" gives |
|---|---|
length() |
9 |
charAt(1) |
'a' |
indexOf("latte") |
4 (or -1 if absent) |
contains("oat") |
true |
substring(0, 3) |
"oat": start included, end excluded |
replace("oat", "soy") |
"soy latte" |
strip() |
removes spaces at both ends |
To compare strings, use equals, never ==:
if (order.equals("latte")) { ... }
if (order.equalsIgnoreCase("LATTE")) { ... }== asks "are these the very same object?", and two strings with identical letters can be different objects, for example when one was typed in by a customer. equals compares the characters.
+ joins strings, working left to right. Once one side is a string, the next + joins text rather than adding numbers. For tidy output, String.format("%s owes %d cents", name, cents) fills placeholders in order.
The shortcut
For any string line, ask two questions: "Is the result stored?" and "What are the start and end index?" The first catches the immutability trap; the second handles substring and charAt, which count from zero, with substring stopping before its end index.
Start
String drink = "espresso";
Drills
Answer fast — trust the rule.
String drink = "mocha"; drink.replace("m", "M"); System.out.println(drink); prints what?
What is "espresso".substring(2, 5)?
Which is the reliable way to check whether a customer typed exactly "latte"?
What does System.out.println(1 + 2 + " cups" + 1 + 2); print?
Remember
- A String never changes; store the new string a method returns.
- Ask "is it stored?" and "which indexes?";
substringexcludes its end. - Traps:
==instead ofequals, and+switching from maths to joining.
