What is Scanner.nextLine() in Java?

Overview

The Scanner.nextLine() is a method in the Java Scanner class that returns a line of text that is read from the scanner object. This method can be used to read an entire line of text or to read input until a particular character or sequence is encountered. It is typically used to read user input from the console.

The Scanner.nextLine() is different from other Scanner methods. For example, the nextInt() method reads an entire line of text, rather than stopping at a delimiter character.

Syntax

Let's view the syntax for this method:

Scanner.nextLine()

Parameters

This method does not take any parameters.

Return value

This method returns the next line of text that is read from the scanner object.

Code example

Let's look at the code below:

import java.util.Scanner;
class HelloWorld {
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("Hello, " + name + "!");
}
}

Enter the input below

In the example above, nextLine() is used to read a line of text (the user's name) from the console. The input is then stored in the name variable and printed to the console.

Note: The nextLine() returns an empty string if called immediately after another Scanner method, such as nextInt(). This is because nextInt() reads only the next token (int), and not the rest of the lines. Below is the code example to demonstrate this:

import java.util.Scanner;
class HelloWorld {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// consume the newline character
scanner.nextLine();
// nextLine() returns an empty string after nextInt() is called
String name = scanner.nextLine();
System.out.println("Hello, " + name + ". You are " + age + " years old.");
}
}

Enter the input below

This is fixed by adding a call to scanner.nextLine(). This consumes the newline character that is left over from the previous call to nextInt(). This allows us to correctly read the user's name.

Conclusion

We learned how to use the nextLine() method in the Java Scanner class. This method can be used to read an entire line of text or stop reading input at a particular character or sequence. It is often used when reading user input from the console.

Free Resources