Strings and Their Methods
Strings are immutable, so methods like toUpperCase and substring return new strings, and text is compared with equals rather than ==.
Transform text without assuming a String object changes in place.
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.