Java Scanner nextLine()

In this guide, you will learn about the Scanner nextLine() method in Java programming and how to use it with an example.

1. Scanner nextLine() Method Overview

Definition:

The nextLine() method of the Scanner class in Java is used to get the input as a string. This method advances the scanner past the current line and returns the input that was skipped.

Syntax:

public String nextLine()

Parameters:

No parameters are needed for this method.

Key Points:

- The method reads the rest of the current line, even if it's empty.

- It can be used multiple times consecutively to read multiple lines.

- It doesn't require the input to be of any specific type, meaning it can read any kind of string until a new line is encountered.

- One must be cautious when mixing nextLine() with other next...() methods because other methods may not consume the entire line, leaving the newline character in the buffer.

2. Scanner nextLine() Method Example

import java.util.Scanner;

public class ScannerExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter your name:");
        String name = scanner.nextLine();

        System.out.println("Enter your address:");
        String address = scanner.nextLine();

        System.out.println("Your name is: " + name);
        System.out.println("Your address is: " + address);
    }
}

Output:

Enter your name:
John Doe
Enter your address:
123 Main St
Your name is: John Doe
Your address is: 123 Main St

Explanation:

In the above example, we created an instance of the Scanner class. We then use the nextLine() method twice to read two strings: name and address. As you can see, this method reads the entire line until it encounters a new line (i.e., until the user hits Enter). The entered strings are then printed to the console.

Comments