String class added methods in Java 11

Java 11 introduced several new methods in the java.lang.String class. Here's a detailed explanation of each:

  1. isBlank(): This method checks if a string is empty or contains only white space characters. It's a more comprehensive check than the isEmpty() method, which only checks if a string is empty.

  2. " ".isBlank(); // returns true "".isBlank(); // returns true "Hello".isBlank(); // returns false
    java

    Before Java 11, to check if a string was blank, you would have to use something like str.trim().isEmpty(), which is not as clear or efficient.

  3. lines(): This method returns a stream of lines extracted from the string, separated by line terminators (\n\r\r\n).

    "Hello\nWorld".lines().forEach(System.out::println); // prints: // Hello // World
    java

    Before Java 11, you would have to use something like str.split("\n") to split a string into lines, which returns an array, not a stream, and doesn't handle different line terminators.

  4. strip()stripLeading()stripTrailing(): These methods remove white space from the string. strip() removes white space from both ends of the string, stripLeading() from the beginning, and stripTrailing() from the end. These methods consider a wider range of white space characters than trim().

    " Hello World ".strip(); // returns "Hello World" " Hello World ".stripLeading(); // returns "Hello World " " Hello World ".stripTrailing(); // returns " Hello World"
    java

    Before Java 11, you would use the trim() method to remove white space from both ends of a string. However, trim() only removes ASCII space characters (code 32), while strip() methods remove all kinds of white space.

  5. repeat(int n): This method repeats the string n times.

    "Hello".repeat(3); // returns "HelloHelloHello"
    java

    Before Java 11, to repeat a string, you would have to use a loop or a third-party library like Apache Commons Lang.

Post a Comment

Previous Post Next Post