Java 11 – String API

  • Post author:
  • Post category:Java 11
  • Post comments:1 Comment
Java 11 - String API

This topic is about Java 11 – String API.

Java 11 introduced multiple enhancements to String.

  • String.repeat(int) − Repeats a string given number of times. Returns the concatenated string.
  • String.isBlank() − Checks if a string is empty or have white spaces only.
  • String.strip() − Removes the leading and trailing whitespaces.
  • String.stripLeading() − Removes the leading whitespaces.
  • String.stripTrailing() − Removes the trailing whitespaces.
  • String.lines() − Return the stream of lines of multi-line string.

Consider the following example −

ApiTester.java

import java.util.ArrayList;
import java.util.List;

public class APITester {
   public static void main(String[] args) {
      String sample = " abc ";
      System.out.println(sample.repeat(2)); // " abc  abc "
      System.out.println(sample.isBlank()); // false
      System.out.println("".isBlank()); // true
      System.out.println("   ".isBlank()); // true
      System.out.println(sample.strip()); // "abc"
      System.out.println(sample.stripLeading()); // "abc "
      System.out.println(sample.stripTrailing()); // " abc"
      sample = "This\nis\na\nmultiline\ntext.";

      List<String> lines = new ArrayList<>();

      sample.lines().forEach(line -> lines.add(line));
      lines.forEach(line -> System.out.println(line));
   }
}

Output

abc  abc 
false
true
true
abc
abc 
 abc
This
is
a
multiline
text.

In this topic we learned about Java 11 – String API. To know more.

This Post Has One Comment

Leave a Reply