New Methods in the String Class – Java 11 and 12

Introduction

A few useful methods have been added to the String class in Java 11 and 12. Let us learn about the new methods in the String class in Java (Java 11 and 12).

New Methods in String Class

We will learn about the below methods added in Java 11.

  • Strip, StripLeading and StripTrailing
  • IsBlank
  • Lines
  • Repeat

and the following methods in Java 12.

  • Indent
  • Transform

Strip, StripLeading and StripTrailing

The strip() method will strip the leading and trailing whitespaces in a string and returns the stripped string. In other words, if will return a substring of the string starting with the first code point that is not a white space till the last code point that is not a white space. In short, this strips white space from the beginning and the end of a string.

String s = "  Java  ";
System.out.println(s);
System.out.println(s.strip());

From the above example, we have white spaces at the beginning and the end of the string. Calling strip() removes those and returns a new string which doesn’t have leading and trailing white space characters in it. The output is:

  Java  //Note: there is whitespace at the end of the string as well
Java

If the string has only white space characters, then it will return an empty string.

String s = "  ";
System.out.println(s.strip()); //prints an empty string

StripLeading and StripTrailing

  • The stripLeading method returns a string with only the leading white space(s) removed.
    • It returns a substring starting with the first code point which is not a white space till the last code point of the string.
  • The stripLeading method returns a string with only the trailing white space(s) removed.
    • It returns a substring starting with the first code point till the last code point which is not a white space.

Example is shown below.

String s = "  Java  ";
System.out.println(s.stripLeading());

s = "  Java  ";
System.out.println(s.stripTrailing());

Prints,

Java  //Note: there is whitespace at the end of the string
  Java //Has whitespace at the beginning of the string

IsBlank

This is a simple method which returns a true if the 

  • string is empty or
  • has only white space characters in it.

and false otherwise.

This is different from the isEmpty() method which returns true iff the length is 0. Hence for strings which have only white space(s) in it, isEmpty() will return a false whereas, isBlank() will return true.

String s = "abcd";
System.out.println(s.isBlank()); //false
System.out.println(s.isEmpty()); //false

s = "   ";
System.out.println(s.isBlank()); //true
System.out.println(s.isEmpty()); //false

For empty strings, both isBlank() and isEmpty() will return a true.

String s = "";
System.out.println(s.isBlank()); //true
System.out.println(s.isEmpty()); //true

String lines method

The lines() method returns a Stream<String>. It splits the string into multiple lines, each line is a string and returns a stream of that. It separates the lines by line terminators.

As per the definition this method uses, a line terminator is one of the following:

  • A line feed character “\n” (U+000A)
  • A carriage return character “\r” (U+000D), or 
  • A carriage return followed immediately by a line feed “\r\n” (U+000D U+000A)

Let us start with a simple example. We have a string with two new line characters in it. Calling lines will split it into three strings and returns a stream which we print using forEach.

String s = "Java\nis\nfun";
s.lines()
        .forEach(System.out::println);

Prints,

Java
is
fun

Multiple consecutive new line characters

If we have multiple consecutive line feed characters, it will result in a string being empty.

String s = "Java\n\nis\nfun";
s.lines()
        .forEach(System.out::println);
Java

is
fun

The two “\n\n” resulted in an empty string + a new line.

New line at end of the string

Let us see what happens when we have one or more line feed characters at the end of the string.

String s = "Java\nis\nfun\n";
s.lines()
        .forEach(System.out::println);

In the above code, there is a new line at the end of the given string. However, this doesn’t impact the result when compared to the first example where there was no \n at the end. This prints,

Java
is
fun

But if we have two \n at the end, then it prints an empty string + \n at the end.

String s = "Java\nis\nfun\n\n";
s.lines()
        .forEach(System.out::println);
System.out.println("----");     
Java
is
fun

----

Calling lines on an empty string

If we call the lines() method on an empty string, then it will return an empty stream.

System.out.println("".lines().findFirst()); //Optional.empty

We called findFirst() on the returned stream. It returned an empty Optional.

Comparing lines() with split

We could get the same behaviour as lines() by using String#split method and split on \R or \n as shown below.

String s = "Java\nis\nfun";
System.out.println(Arrays.toString(s.split("\n"))); //[Java, is, fun]
System.out.println(Arrays.toString(s.split("\\R"))); //[Java, is, fun]
System.out.println(s.lines().collect(Collectors.toList())); //[Java, is, fun]

But using lines, we can get a better performance. Hence, it is preferable to use lines() in scenarios like these.

String repeat method

The repeat method takes an integer (count) and returns a string whose value is the concatenation of the string repeated count times. In other words, it concatenates the string count times and returns a new string.

System.out.println("ab".repeat(2)); //abab
System.out.println("ab".repeat(1)); //ab

If this string is empty or count is zero, then it will return an empty string.

System.out.println("".repeat(2)); //returns an empty string
System.out.println("ab".repeat(0)); //returns an empty string

If we pass a negative value for count, then it throws an IllegalArgumentException.

//throws java.lang.IllegalArgumentException: count is negative: -1
System.out.println("ab".repeat(-1));

Indenting strings

The indent() method, added in Java 12, adds or removed n number of white space characters. It takes an integer parameter, n, and indents each line of the string based on it. It does the following:

  • Separates the string into lines using the lines() method we saw before.
  • For each line:
    • It adds or removes white space at the beginning of the line by the below rule:
      • If n > 0, then it adds n spaces at the beginning of the line.
      • If n < 0, then up to n spaces will be removed at the beginning of the line. (Note: The string might have less the white spaces at the start).
    • It suffixes each line with a line feed (“\n”) character (i.e., normalizes line terminators).
    • It joins the individual lines back and returns it.

Let us start with a simple example:

String s = "ab\ncd";
System.out.println(s.indent(3));

After it applies the lines() method on the passed string, we would have two lines. We have passed n as 3 and hence it will add 3 spaces to the start of each line. This results in:

//Note: there are three spaces at the beginning of each line
   ab
   cd

Passing n as 0, the lines remain unchanged.

String s = "ab\ncd";
System.out.println(s.indent(0));
ab
cd

String indent – Passing negative value for n

Let us pass a negative value for n to remove white spaces. The below example uses a string which doesn’t have any spaces at the start of each line and hence it cannot remove anything.

String s = "ab\ncd";
System.out.println(s.indent(-2));
ab
cd

The next two examples show using strings which have one or more white spaces at the start of a line. 

String s = "ab\n  cd"; //has 2 spaces at the start of the second line
System.out.println(s.indent(-2));

The second has two white spaces and since we passed -2 as n, it will remove both the white space characters. This outputs:

ab
cd

If we had three space characters, then with n = -2, it can remove only two of those space characters.

String s = "ab\n   cd"; //has 3 spaces at the start of the second line
System.out.println(s.indent(-2));
ab
 cd

String indent with tab characters

It considers tab character as a single character. The below example has a tab character and two spaces at the beginning of the second line. Hence, passing n = -2, will remove the tab and the first space character.

Strings = "ab\n\t  cd"; // second line has a tab + 2 spaces
System.out.println(s.indent(-2));
ab
 cd

On the other hand, if the line had two spaces and a tab character, it will remove only the two spaces and leave the tab as shown below.

String s = "ab\n  \tcd"; // second line has 2 spaces + tab
System.out.println(s.indent(-2));
ab
    cd

String transform

The transform() is a simple function which takes a java Function functional interface applies it to the string and returns the result. It propagates any exception thrown by the function.

Integer r = "12".transform(Integer::valueOf);
System.out.println(r);

Above, we are passing a function (as a method reference) to convert the string to an integer.

Conclusion

This concludes the post on the new methods in the String class added in Java 11 and 12. Hope it would have been helpful.

Leave a Reply