Java 11 introduced six new methods to the String class to enhance string manipulation, particularly with better Unicode support and streamlined operations.
1. isBlank()
- Purpose: Returns true if the string is empty or contains only whitespace characters (including Unicode whitespace), otherwise false.
- Use Case: Useful for validating input strings to check if they are effectively empty.
- Syntax: public boolean isBlank()
- Example:
String s1 = ""; // Empty string
String s2 = " \t"; // Whitespace only
String s3 = "Hello";
System.out.println(s1.isBlank()); // true
System.out.println(s2.isBlank()); // true
System.out.println(s3.isBlank()); // false
Code language: JavaScript (javascript)
2. lines()
- Purpose: Returns a Stream<String> of lines extracted from the string, split by line terminators (\n, \r, or \r\n).
- Syntax: public Stream<String> lines()
-
Use Case: Ideal for processing multi-line strings, such as parsing text files or logs.
- Example
String text = "Line 1\nLine 2\rLine 3";
text.lines().forEach(System.out::println);
// Output:
// Line 1
// Line 2
// Line 3
Code language: PHP (php)
3. repeat(int count)
- Purpose: Returns a new string that is the original string repeated count times. Throws IllegalArgumentException if count is negative.
-
Use Case: Simplifies creating repeated patterns, e.g., for formatting or generating test data.
- Syntax: public String repeat(int count)
- Example:
String s = "Hi ";
System.out.println(s.repeat(3)); // Hi Hi Hi
System.out.println(s.repeat(0)); // (empty string)
Code language: JavaScript (javascript)
4. strip()
- Purpose: Removes all leading and trailing whitespace (based on Character.isWhitespace(), which supports Unicode whitespace) and returns the resulting string.
-
Use Case: Preferred over trim() for consistent whitespace removal, especially with Unicode text.
- Syntax: public String strip()
- Example:
String s = "\u2002 Hello \u2002";
System.out.println(s.strip()); // Hello
System.out.println(s.trim()); // Hello (trim() misses Unicode whitespace > U+0020)
Code language: JavaScript (javascript)
5. stripLeading()
- Purpose: Removes only leading whitespace (Unicode-aware) and returns the resulting string.
-
Use Case: Useful when you need to preserve trailing spaces, e.g., in formatted output.
- Syntax: public String stripLeading()
- Example:
String s = " Hello ";
System.out.println(s.stripLeading()); // Hello
Code language: JavaScript (javascript)
6. stripTrailing()
- Purpose: Removes only trailing whitespace (Unicode-aware) and returns the resulting string.
-
Use Case: Handy for cleaning up strings while keeping leading spaces intact.
- Syntax: public String stripTrailing()
- Example:
String s = " Hello ";
System.out.println(s.stripTrailing()); // Hello
Code language: JavaScript (javascript)
The above methods make string handling in Java 11 more efficient and flexible, especially for modern applications dealing with diverse text inputs.