Close

Java 11 - String Changes

[Updated: Sep 29, 2018, Created: Sep 28, 2018]

Java 11, added various new methods in java.lang.String. Let's see each one of them with examples.

Stripping white spaces

Following new methods have been added to remove white spaces:

public String strip()
public String stripLeading()
public String stripTrailing()

Example:

package com.logicbig.example;

public class StringStripExample {
  public static void main(String[] args) {
      String s = "  test string  ";
      System.out.printf("'%s'%n", s);
      String striped = s.strip();
      System.out.printf("strip():%n '%s'%n", striped);

      striped = s.stripLeading();
      System.out.printf("stripLeading():%n '%s'%n", striped);

      striped = s.stripTrailing();
      System.out.printf("stripTrailing():%n '%s'%n", striped);
  }
}
'  test string  '
strip():
'test string'
stripLeading():
'test string '
stripTrailing():
' test string'

strip() vs trim()

strip() is Unicode whitespace aware, whereas the existing method trim() removes any space which is less than or equal to (\u0020).

Following example uses medium mathematical space \u205F, (list of whitespace unicodes)

public class StringStripVsTrimExample {
  public static void main(String[] args) {
      String s = "test string\u205F";
      String striped = s.strip();
      System.out.printf("'%s'%n", striped);

      String trimmed = s.trim();
      System.out.printf("'%s'%n", trimmed);
  }
}
'test string'
'test stringāŸ'

See also JDK-8200378.

Blank strings

public boolean isBlank()

This method returns true if the string is empty or contains only white space codepoints, otherwise false. The existing method isEmpty() returns true if length() is 0.

public class StringIsBlankExample {

  public static void main(String[] args) {
      String s = "  ";
      //old isEmpty() method
      boolean empty = s.isEmpty();
      System.out.println(empty);
      //new isBlank()
      boolean blank = s.isBlank();
      System.out.println(blank);
  }
}
false
true

Streaming lines

public Stream<String> lines()
public class StringLinesExample {
  public static void main(String[] args) {
      String s = "jujube\nsatsuma\nguava";
      s.lines()
       .forEach(System.out::println);
  }
}
jujube
satsuma
guava

Repeating

public String repeat(int count)

This method returns a string whose value is repeated 'count' times

public class StringRepeatExample {
  public static void main(String[] args) {
      String s = "-";
      String newString = s.repeat(10);
      System.out.println(newString);
  }
}
----------

Example Project

Dependencies and Technologies Used:

  • JDK 11
Java 11 - New String methods Select All Download
  • java-11-string-changes
    • src
      • com
        • logicbig
          • example
            • StringRepeatExample.java

    See Also