15.1 New String Methods Explained
Java SE 11 introduced several new methods to the String class, enhancing its functionality and making common string operations more efficient. Understanding these new methods is crucial for modern Java development.
Key Concepts
1. isBlank()
The isBlank()
method checks if a string is empty or contains only whitespace characters. It returns a boolean value.
Example
String str1 = ""; String str2 = " "; String str3 = "Hello"; System.out.println(str1.isBlank()); // true System.out.println(str2.isBlank()); // true System.out.println(str3.isBlank()); // false
2. lines()
The lines()
method splits a string into a stream of lines, using line terminators (like \n or \r\n) as delimiters.
Example
String str = "Line 1\nLine 2\r\nLine 3"; str.lines().forEach(System.out::println); // Output: // Line 1 // Line 2 // Line 3
3. strip()
The strip()
method removes leading and trailing whitespace from a string. It is similar to trim()
but provides better Unicode support.
Example
String str = " Hello World! "; System.out.println(str.strip()); // "Hello World!"
4. stripLeading()
The stripLeading()
method removes only the leading whitespace from a string.
Example
String str = " Hello World! "; System.out.println(str.stripLeading()); // "Hello World! "
5. stripTrailing()
The stripTrailing()
method removes only the trailing whitespace from a string.
Example
String str = " Hello World! "; System.out.println(str.stripTrailing()); // " Hello World!"
6. repeat(int count)
The repeat(int count)
method repeats the string a specified number of times.
Example
String str = "Java"; System.out.println(str.repeat(3)); // "JavaJavaJava"
Examples and Analogies
Think of the new String methods as tools in a toolbox. Each tool (method) serves a specific purpose, making common tasks easier and more efficient. For instance, isBlank()
is like a sensor that detects if a surface is empty or just filled with dust (whitespace). The lines()
method is like a paper cutter that splits a document into individual lines.
For example, if you are processing a large text file, the lines()
method allows you to handle each line independently, making the process more manageable. The strip()
method ensures that any unwanted whitespace is removed, similar to cleaning a surface before applying a new coat of paint.
By mastering these new String methods, you can write cleaner, more efficient code, making your Java applications more robust and maintainable.