Card 03/ 09

ExampleDifficulty: Beginner1 min

Trimming a Line From a File and Losing the Result

A file of account codes, one per line, with a stray space at the end of some of them. The code strips the whitespace and the lookup still fails on exactly those lines.

java
for (String line : Files.readAllLines(path)) {
    line.strip();
    Account found = accounts.get(line);
    System.out.println(line + " -> " + found);
}
text
AC-1001 -> Account[1001]
AC-1002   -> null

Line 2 built a stripped copy and dropped it on the floor. line still has its trailing spaces, so the map lookup on line 3 is asking for a key that is not there — and a map lookup that finds nothing returns null rather than complaining.

Put this beside the upper-casing example and the shared fact is the whole lesson: both methods returned a new string, and the only difference is whether anything kept it. One line assigned the result and worked; one did not and failed silently.

line = line.strip(); is the fix, and the habit worth forming is to look for the = whenever you see a String method being called at all.