Card 03/ 09
String Immutability Example: A Stripped Line That Was Never Kept
Account codes with trailing spaces, a strip() call, and lookups that still fail on exactly those lines.
Strings are immutable, so strip() and every other String method return a new string and leave the original unchanged. Calling one without assigning its result throws the new string away. A file of account codes, one per line, with stray spaces at the end of some lines. The code strips the whitespace, and the lookup still fails on exactly those lines:
for (String line : Files.readAllLines(path)) {
line.strip();
Account found = accounts.get(line);
System.out.println(line + " -> " + found);
}AC-1001 -> Account[number=1001]
AC-1002 -> nullLine 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 String shouted = name.toUpperCase();, where the result is kept and works, 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.
← → move through sections and cards