Common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most String bugs come from a few mistakes: == instead of equals(), a result that was never stored, and an index that is one too far. Spot them quickly, then put the whole module to work on real problems.
Mistakes and fixes at a glance
A city typed as " Delhi " fails the check equals("Delhi"), even after trim(). Strings never change, so the most common String bug is a result that was never stored.
Example 1 · The trim() that did nothing
public class TrimTrap { public static void main(String[] args) { String city = " Delhi "; city.trim(); System.out.println(city.equals("Delhi")); city = city.trim(); System.out.println(city.equals("Delhi")); }}false true
What this code does
- Line 4 makes a trimmed copy, but nothing keeps it, so
citystill has its spaces. - After
city = city.trim();the variable holds the clean text andequals()givestrue.
Review: Change case, trim and replace (opens in a new tab). The other common mistakes, each with the fix:
==for text →falsefor typed text that looks the same → useequals(). Review: Compare Strings (opens in a new tab)charAt(s.length())orsubstring(2, 99)→StringIndexOutOfBoundsException→ the last index islength() - 1. Review: Characters and index positions (opens in a new tab)'P' + 'S'prints 163 → start with text:"" + 'P' + 'S'.split(".")orsplit(" ")with extra spaces →split("\\."),trim().split("\\s+"). Review: Split, join and parse (opens in a new tab)
Spot the bug
Each snippet looks almost right but does the wrong thing. Read what it should do, tap the wrong line, then check the fix. Ask first: is the text compared, stored and indexed correctly?
Find the bug
Find the String bug
Select the line that is wrong.
This should print Welcome when the user types admin.
Check before you cut
A form gets ravi.gmail.com, with no @, and substring(0, -1) would stop the program. Check first: test indexOf() for -1, and isEmpty() before charAt(0).
Example 2 · Check indexOf() before substring()
public class SafeUser { public static void main(String[] args) { String email = "ravi.gmail.com"; int at = email.indexOf('@'); if (at == -1) { System.out.println("No @ in " + email); } else { System.out.println("User: " + email.substring(0, at)); } }}No @ in ravi.gmail.com
What this code does
- The email has no
@, soatis -1 and the first branch runs. - Without the check,
substring(0, -1)would stop the program withStringIndexOutOfBoundsException.
Which tool fits?
Most String problems are one of five moves: read one character, cut a part, split into parts, compare, or build new text. Sort each job to its tool.
Classify
Pick the String tool
Tap a job, then tap the tool that does it.
Finish up
Mark complete & continue
Next: Must-do problems: Strings