Leah
PRO
2 months ago
Leahcountry asked

What is the purpose of input.nextLine() in Java, and how is it different from other input methods like nextInt()?

Abhay Jajodia
Expert
last month
Abhay Jajodia answered

Hi Yeah, great question.

In Java, input.nextLine() is used to read an entire line of text entered by the user — including spaces — up until they press ENTER. This makes it ideal when you're asking for inputs like full names, addresses, or any sentence.

Here's how it works:

import java.util.Scanner;

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

        System.out.println("Enter your full name:");
        String fullName = input.nextLine();

        System.out.println("Hello, " + fullName);
    }
}

If the user types John Doe, the output will be:

Hello, John Doe

Now, how is it different from nextInt() or next()?

  • nextInt() only reads the integer.

  • next() reads a single word (stops at a space).

  • nextLine() reads the entire line, including any spaces, until ENTER is pressed.

This also means that if you use nextInt() followed by nextLine(), you may get unexpected behavior because nextInt() doesn't consume the newline character. That’s something to watch out for.

If you have more questions, I am here to help.

Java
This question was asked as part of the Learn Java Basics course.