Java 11 New String Methods

Introduction

Java 11 introduced several new methods to the String class, providing more convenience and efficiency in string manipulation. These methods simplify common string operations and enhance the overall functionality of the String class. This guide will cover the new methods added in Java 11, including isBlank(), lines(), strip(), stripLeading(), stripTrailing(), repeat(), and indent().

Key Points:

  • Convenience Methods: The new methods provide more straightforward ways to perform common string operations.
  • Whitespace Handling: Improved methods for handling and manipulating whitespace.
  • Functional Enhancements: Additional functionality for working with strings in modern Java applications.

New String Methods in Java 11

1. isBlank()

The isBlank() method checks if a string is empty or contains only whitespace characters. It returns true if the string is blank, otherwise false.

Example:

public class IsBlankExample {
    public static void main(String[] args) {
        String str1 = "";
        String str2 = "   ";
        String str3 = "Hello";

        System.out.println(str1.isBlank()); // true
        System.out.println(str2.isBlank()); // true
        System.out.println(str3.isBlank()); // false
    }
}

Output:

true
true
false

Explanation:

  • str1 and str2: These strings are either empty or contain only whitespace, so isBlank() returns true.
  • str3: This string contains non-whitespace characters, so isBlank() returns false.

2. lines()

The lines() method returns a stream of lines extracted from a string, splitting it by line terminators. This is useful for processing multi-line text.

Example:

import java.util.stream.Collectors;

public class LinesExample {
    public static void main(String[] args) {
        String multilineString = "Hello\nWorld\nJava 11";

        // Convert the lines to a list
        var linesList = multilineString.lines().collect(Collectors.toList());

        System.out.println(linesList); // [Hello, World, Java 11]
    }
}

Output:

[Hello, World, Java 11]

Explanation:

  • lines() Method: Splits the string into lines and returns them as a stream.
  • Collectors.toList(): Collects the stream of lines into a list for easy manipulation.

3. strip(), stripLeading(), and stripTrailing()

These methods are used for removing whitespace from strings. strip() removes leading and trailing whitespace, stripLeading() removes only leading whitespace, and stripTrailing() removes only trailing whitespace.

Example:

public class StripExample {
    public static void main(String[] args) {
        String str = "   Hello World   ";

        System.out.println("Original: '" + str + "'");
        System.out.println("strip(): '" + str.strip() + "'");               // 'Hello World'
        System.out.println("stripLeading(): '" + str.stripLeading() + "'"); // 'Hello World   '
        System.out.println("stripTrailing(): '" + str.stripTrailing() + "'");// '   Hello World'
    }
}

Output:

Original: '   Hello World   '
strip(): 'Hello World'
stripLeading(): 'Hello World   '
stripTrailing(): '   Hello World'

Explanation:

  • strip(): Removes both leading and trailing whitespace.
  • stripLeading(): Removes only leading whitespace.
  • stripTrailing(): Removes only trailing whitespace.

4. repeat(int count)

The repeat() method repeats a string a specified number of times, returning the concatenated result.

Example:

public class RepeatExample {
    public static void main(String[] args) {
        String str = "Java";

        System.out.println(str.repeat(3)); // JavaJavaJava
    }
}

Output:

JavaJavaJava

Explanation:

  • repeat(3): Concatenates the string "Java" three times, resulting in "JavaJavaJava".

5. indent(int n)

The indent() method adjusts the indentation of each line in the string. Positive values add spaces, while negative values remove spaces.

Example:

public class IndentExample {
    public static void main(String[] args) {
        String str = "Line 1\nLine 2\nLine 3";

        System.out.println("Original:\n" + str);
        System.out.println("Indented:\n" + str.indent(4));   // Indents each line with 4 spaces
        System.out.println("Reduced Indent:\n" + str.indent(-2)); // Reduces indentation by 2 spaces
    }
}

Output:

Original:
Line 1
Line 2
Line 3
Indented:
    Line 1
    Line 2
    Line 3
Reduced Indent:
Line 1
Line 2
Line 3

Explanation:

  • indent(4): Adds four spaces to the beginning of each line.
  • indent(-2): Removes up to two spaces from the beginning of each line.

Use Cases for New String Methods

Use Case 1: Data Cleaning

  • strip(): Clean user input by removing unwanted whitespace.
  • isBlank(): Validate fields that should not be empty or whitespace-only.

Use Case 2: Text Processing

  • lines(): Process multi-line text files by splitting them into lines for analysis.
  • indent(): Format output for readability by adjusting line indentation.

Use Case 3: String Manipulation

  • repeat(): Generate repeated patterns or fill strings with repeated characters.

Conclusion

Java 11’s new string methods provide developers with more tools to handle common string operations efficiently. These methods improve code readability and simplify tasks that previously required custom solutions or additional libraries.

Summary:

  • isBlank(): Checks if a string is empty or contains only whitespace.
  • lines(): Splits a string into lines for processing.
  • strip(), stripLeading(), stripTrailing(): Remove whitespace from strings.
  • repeat(): Repeat a string multiple times.
  • indent(): Adjust the indentation of each line in a string.

By leveraging these new methods, you can write cleaner, more efficient code in your Java applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top