Java 11, released in September 2018, marked an exciting time for developers working with strings. This version introduced some significant changes, making string manipulation easier, more efficient, and readable. In this post, we’ll explore four new string methods: isBlank(), strip(), repeat(), and lines(), providing insights into their usage and advantages.
1. isBlank(): Checking for Whitespace
The isBlank() method returns true if the string is empty or contains only whitespace characters.
Example:
String str1 = ""; String str2 = " "; System.out.println(str1.isBlank()); // true System.out.println(str2.isBlank()); // true
2. strip(): Removing Whitespace
While trim() removes whitespace from the beginning and end of a string, it considers only characters that have ASCII value <= 32 as whitespace. The new strip(), stripLeading(), and stripTrailing() methods understand all Unicode whitespace characters.
Example:
String str = " Hello World! "; System.out.println(str.strip()); // "Hello World!"
3. repeat(): Repeating Strings
The repeat(int n) method allows you to repeat a string n times. It is a convenient way to create repeated patterns.
Example:
String str = "Java 11 "; System.out.println(str.repeat(3)); // "Java 11 Java 11 Java 11 "
4. lines(): Handling Multiline Strings
The lines() method returns a stream of substrings, extracted by splitting the invoking string around line terminators.
Example:
String str = "Line1\nLine2\rLine3"; str.lines().forEach(System.out::println); // Output: // Line1 // Line2 // Line3
Summary
Java 11’s new string methods not only enhance readability but also add significant functionalities that are handy for modern programming. These methods simplify common tasks, such as checking for blank strings, handling whitespace, repeating strings, and working with multiline strings. Developers should consider adopting these methods to write more concise and expressive code.
Do remember to upgrade your application to at least Java 11 to take advantage of these new features. Experimenting with them in your daily coding practices will undoubtedly lead to more maintainable and clear code. Happy coding!
📚 Further Reading & Related Topics
If you’re exploring Java 11’s String enhancements and core improvements, these related articles will provide deeper insights into Java’s evolution:
• Java 13 and the Evolution of Switch Expressions: A Deeper Dive – Learn how Java’s syntax has evolved with more expressive and concise switch expressions, improving readability and reducing boilerplate code.
• Java 16 and the Standardization of Records: Simplifying Data Classes – Explore how Java continues to enhance productivity by introducing modern features that improve data modeling and structure.









Leave a comment