Skip to Content
Course content

21: String Methods in Depth

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this specific bug more times than I can count, usually during a first-year internship or a junior dev's first week on the job. You're trying to clean up some user input, you call a method to fix it, and then you're baffled when the data is still "dirty."

String userEmail = "  Developer@Example.com  ";

// We want to trim the whitespace and make it lowercase for the database
userEmail.trim();
userEmail.toLowerCase();

System.out.println("Saving email: '" + userEmail + "'"); 
// Output: Saving email: '  Developer@Example.com  '

The Immutable String Trap

Looking at the code above, it feels like it should work. You called .trim(), then you called .toLowerCase(). But as you can see in the output, the original userEmail string hasn't changed at all. Why?

In Java, String objects are immutable. This means once a String is created in memory, it can never be changed. When you call a method like .trim(), Java isn't modifying the existing string; it's creating a brand new string in memory and returning it to you. If you don't capture that returned value, it simply vanishes into the void, and you're left holding the original, unmodified string.

Reassigning the Result

To fix this, you have to assign the result of the method back to a variable. You can either overwrite the original variable or create a new one. Since we're just cleaning up data, overwriting the original is usually the cleanest approach.

String userEmail = "  Developer@Example.com  ";

// Capture the return values!
userEmail = userEmail.trim().toLowerCase();

System.out.println("Saving email: '" + userEmail + "'"); 
// Output: Saving email: 'developer@example.com'

Notice how I "chained" the methods together. This is a common pattern in Java. Because .trim() returns a String, we can immediately call .toLowerCase() on that resulting string.

Searching and Slicing with contains, startsWith, and substring

Beyond simple cleaning, you'll spend a lot of your time inspecting strings. Instead of using complex regular expressions for everything, Java provides a few high-utility methods that are much more readable.

  • contains(CharSequence s): Returns true if the sequence exists anywhere in the string.
  • startsWith(String prefix) and endsWith(String suffix): Essential for checking file extensions or protocol types (like checking if a URL starts with "https").
  • substring(int beginIndex, int endIndex): This is how you "slice" a string. Just remember: the beginIndex is inclusive, but the endIndex is exclusive.
String filename = "report_2023_final.pdf";

if (filename.endsWith(".pdf")) {
    // Extract just the year (from index 7 to 11)
    String year = filename.substring(7, 11); 
    System.out.println("Processing report for year: " + year);
}

Breaking Strings Apart with split

When you're dealing with CSV files or data coming from an API, you'll likely use .split(). This method breaks a string into an array based on a delimiter you provide. I'll warn you now: split() takes a regular expression, not just a literal string. This means if you try to split by a period (".") or a pipe ("|"), you'll get weird results because those are special characters in regex. You have to escape them with double backslashes (e.g., \\.).

String tags = "java,programming,software-engineering,mentor";
String[] tagArray = tags.split(",");

for (String tag : tagArray) {
    System.out.println("Tag: " + tag);
}

Dealing with whitespace: isEmpty vs isBlank

If you're using Java 11 or newer, you have a choice between isEmpty() and isBlank(). They sound identical, but they behave very differently in the real world.

  • isEmpty(): Returns true only if the string length is 0. A string containing just a few spaces is not empty.
  • isBlank(): Returns true if the string is empty or contains only white space.

I almost always use isBlank() when validating user input. If a user hits the spacebar five times in a "Required" field, isEmpty() would let that through, but isBlank() will correctly flag it as missing data.




📋 Practical Task

Exercise: Building a Simple Log Entry Parser

In professional software development, you'll often have to parse logs to find specific errors. Your task is to write a program that processes a raw log string and extracts key information.

The Requirements:

  • Start with this raw log entry: String logEntry = " [ERROR] 2023-10-12 14:30:05 - Database connection failed: Timeout occurred ";
  • Clean the entry: Remove the leading and trailing whitespace from the entire string.
  • Identify the level: Check if the string starts with [ERROR]. If it does, print "High Priority Alert!".
  • Extract the Timestamp: Use substring() to extract the date and time (the part between the log level and the hyphen).
  • Isolate the Message: Use split("-") to separate the metadata from the actual error message. Print only the error message, trimmed of any extra spaces.

Expected output should look something like:
High Priority Alert!
Timestamp: 2023-10-12 14:30:05
Message: Database connection failed: Timeout occurred

Rating
0 0

There are no comments for now.

to be the first to leave a comment.