Skip to lesson

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

TrimTrap.javaJava
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"));    }}
Output
false
true

What this code does

  • Line 4 makes a trimmed copy, but nothing keeps it, so city still has its spaces.
  • After city = city.trim(); the variable holds the clean text and equals() gives true.

Review: Change case, trim and replace (opens in a new tab). The other common mistakes, each with the fix:

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.

Round 1 of 6

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

SafeUser.javaJava
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));        }    }}
Output
No @ in ravi.gmail.com

What this code does

  • The email has no @, so at is -1 and the first branch runs.
  • Without the check, substring(0, -1) would stop the program with StringIndexOutOfBoundsException.

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