Java String lines Example

1. Introduction

This blog post is about the lines() method in Java's String class. Introduced in Java 11, lines() is a method that allows for splitting a string into a stream of lines, which is particularly useful for processing multi-line string content.


String.lines() returns a stream of lines extracted from a string, splitting it around line terminators such as \n, \r, or \r\n. This method provides a convenient and efficient way to handle multi-line strings.

2. Program Steps

1. Create a multi-line string.

2. Use the lines() method to split the string into lines.

3. Process and display each line separately.

3. Code Program

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

        // Splitting the string into lines and processing each line
        multiLineString.lines().forEach(line -> System.out.println("Processed: " + line));


Processed: Line 1
Processed: Line 2
Processed: Line 3


1. multiLineString is defined as a string containing three lines, separated by newline characters (\n).

2. The lines() method is called on multiLineString. It splits the string into a stream of lines.

3. forEach is used to iterate over each line in the stream. In this example, each line is prefixed with "Processed: " and printed.

4. The output shows each line being processed and displayed separately, demonstrating the ease of handling multi-line strings with String.lines().