Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
21: String Methods in Depth
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)andendsWith(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: thebeginIndexis inclusive, but theendIndexis 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
There are no comments for now.