Java 11 String methods| lines strip isBlank examples| new features

In this blog post, we’ll explore six new methods introduced in the String class in Java 11.

JDK 11 - String Methods

Java 11 has added a few methods to the String class, aiming to simplify coding styles and improve performance.

  • lines() example

    This method returns a Stream of strings separated by line breaks from multi-line strings.

    Syntax:

    Stream<String> lines()
    Stream lines = string.lines();
    

    In older versions, you could achieve a similar result using the following stream:

    String linesExample= string.lines()
    .map(String::trim)
    .collect(joining("\n"));
    

    Example:

    lines() method is not Unicode aware compliant.

    String multiLinesString = "String\\nlines\\ndemo\\n";
    multiLinesString.lines().forEach(System.out::println); // returns String lines demo
    
  • strip() example

    This method removes Unicode whitespace characters from a string, behaving similarly to the trim() method.

    strip() method is not Unicode aware compliant.

    System.out.println(" cloud".strip()); // prints "cloud"
    System.out.println("hadoop ".strip()); // prints "hadoop"
    System.out.println(" cloudhadoop ".strip()); // prints "cloudhadoop"
    
  • stringLeading() method

    This method removes a leading whitespace character from String.

    System.out.println(" cloud".stringLeading()); // prints "cloud"
    System.out.println("hadoop ".stringLeading()); // prints "hadoop"
    System.out.println(" cloudhadoop ".stringLeading()); // prints "cloudhadoop "
    
  • stringTrailing() example

    This method removes trailing whitespace characters from a String.

    stripTrailing() + stripLeading() is equivalent to the strip() method.

    System.out.println(" cloud".stripTrailing()); // prints " cloud"
    System.out.println("hadoop ".stripTrailing()); // prints "hadoop"
    System.out.println(" cloudhadoop ".stripTrailing()); // prints " cloudhadoop"
    
  • isBlank() example

    This method checks if the string is empty or only contains whitespace characters.

    System.out.println(" abc".isBlank()); // prints false
    System.out.println("a1 ".isBlank()); // prints false
    System.out.println(" ".isBlank()); // prints true
    
  • repeat(int) example

This method returns the string repeated a specified number of times, with the repetition count configured as a parameter.

Conclusion

In this tutorial, we have explored the new methods introduced in Java 11’s String class, accompanied by examples.