Java 11

Java 11 – String API

Java 11 introduced multiple enhancements to String.

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

Consider the following program−

Java11String.java

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

public class Java11String {

	public static void main(String[] args) {
		// 1. Stream of lines of multi-line string
		String str = "This\nis\na\nmultiline\ntext\nstring.";
		List<String> lines = new ArrayList<>();
	    str.lines().forEach(line -> lines.add(line));
	    lines.forEach(line -> System.out.println(line));
	      
		String txt = " xyz ";
	    
		// 2. Removes the leading and trailing whitespaces
	    System.out.println(txt.strip()); 
	    // 3. Removes the leading whitespaces
	    System.out.println(txt.stripLeading()); 
	    // 4. Removes the trailing whitespaces
	    System.out.println(txt.stripTrailing()); 
	    // 5. Repeats a string given number of times
	    System.out.println(txt.repeat(2)); 
	    // 6. Checks if a string is empty or have white spaces only
	    System.out.println(txt.isBlank()); // false
	    System.out.println("".isBlank()); // true
	    System.out.println("   ".isBlank()); // true

	}
}

Output

This
is
a
multiline
text
string.
xyz
xyz 
 xyz
 xyz  xyz 
false
true
true

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs