Back to Java
2026-02-208 min read

String nextLine() (Java)

Learn String nextLine() (Java) step by step with clear examples and exercises.

Why This Matters

The nextLine() method is a crucial part of Java programming, particularly when dealing with user inputs and file reading scenarios. Unlike the next() method, which reads individual words, nextLine() captures an entire line until a newline character (\n) is encountered. This makes it ideal for handling multi-word inputs or reading from files.

In addition to console input, nextLine() can be used to read lines from various sources such as files and network streams, making it a versatile tool for Java developers.

Prerequisites

To fully understand and use the nextLine() method in Java, you should have a solid foundation in the following topics:

  • Basic Java concepts (variables, data types, operators)
  • Control structures (if-else statements, loops)
  • Input and output streams (System.out, Scanner)
  • Understanding of exceptions and exception handling
  • Familiarity with file I/O operations

Core Concept

The nextLine() method is part of the Scanner class in Java, which simplifies reading user input or file content. To use the nextLine() method, you first need to create a Scanner object and specify its source (either console input or a file).

Here's an example that demonstrates using the nextLine() method:

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); // Create a Scanner for console input
System.out.print("Enter a line: ");
String inputLine = scanner.nextLine(); // Read an entire line of text from the console
System.out.println("You entered: " + inputLine); // Print the user's input back to the console
}
}

In this example, we create a Scanner object and use the nextLine() method to read an entire line of text from the console. The user's input is then printed back to the console.

Declaration

The declaration for the nextLine() method in the Scanner class is as follows:

public String nextLine()

This method returns a String containing the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Exception Handling

The nextLine() method may throw two exceptions:

  1. NoSuchElementException - if no line was found
  2. IllegalStateException - if this scanner is closed

To handle these exceptions, you can use a try-catch block as follows:

Scanner scanner = new Scanner(System.in);
try {
String inputLine = scanner.nextLine();
// Use the input line here
} catch (NoSuchElementException e) {
System.err.println("No line found.");
} catch (IllegalStateException e) {
System.err.println("Scanner is closed.");
}

Reading from a File

To read lines from a file using the nextLine() method, you can create a File object and pass it to the Scanner constructor:

import java.io.File;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
File file = new File("example.txt"); // Create a File object for the example.txt file
Scanner scanner = new Scanner(file); // Create a Scanner for the file

while (scanner.hasNextLine()) {
String line = scanner.nextLine(); // Read each line from the file
System.out.println(line); // Print each line to the console
}

scanner.close(); // Close the Scanner when done
}
}

In this example, we create a File object for "example.txt" and use it to create a Scanner object. We then read each line from the file using a loop and print them to the console. Finally, we close the Scanner object when done.

Worked Example

Let's explore a more practical example that demonstrates reading multiple lines from a file and storing them in an array:

import java.io.File;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {
File file = new File("example.txt"); // Create a File object for the example.txt file
Scanner scanner = new Scanner(file); // Create a Scanner for the file

int numLines = (int) file.length(); // Get the number of lines in the file by counting characters minus line separators
String[] lines = new String[numLines]; // Create an array to store the lines

int index = 0;
while (scanner.hasNextLine()) {
lines[index++] = scanner.nextLine(); // Read each line and store it in the array
}

for (String line : lines) {
System.out.println(line); // Print each line to the console
}

scanner.close(); // Close the Scanner when done
}
}

In this example, we first create a File object for "example.txt" and use it to create a Scanner object. We then calculate the number of lines in the file by counting characters minus line separators (assuming each line ends with a newline character). We create an array to store these lines and read each one using a loop, storing them in the array. Finally, we print out all the lines that were read from the file.

Common Mistakes

When working with the nextLine() method, some common mistakes include:

  1. Not consuming the newline character after reading an integer: After reading an integer using the nextInt() method, there's a remaining newline character in the input stream that needs to be consumed before reading the next line. You can do this by calling scanner.nextLine().
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
String inputLine = scanner.nextLine(); // Consume the remaining newline character
  1. Not handling exceptions: Remember to handle exceptions when using the nextLine() method, as it may throw a NoSuchElementException if no line was found or an IllegalStateException if the scanner is closed.
  1. Reading from multiple sources simultaneously: When creating a Scanner, you should specify only one source (either console input or a file). If you try to read from multiple sources, you may encounter unexpected behavior.
  1. Not closing the Scanner object when done: Although not always necessary, it's a good practice to close the Scanner object when you're finished using it to free up system resources:
scanner.close();
  1. Ignoring line separators: When counting lines in a file or comparing strings that may contain line separators, remember to treat them as part of the line (e.g., "\n" instead of just "\r", depending on your platform).
  1. Not accounting for empty lines: If you're reading lines from a file and want to exclude empty lines, use a loop with a condition that checks if the line is not empty before storing it in an array or processing further:
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (!line.isEmpty()) {
// Process the non-empty line here
}
}
  1. Using nextLine() after exhausting input: If you've exhausted all available input (e.g., reading all lines from a file), calling nextLine() will throw a NoSuchElementException. To avoid this, check if there are more lines to read before calling nextLine():
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// Process the line here
}

Practice Questions

  1. Write a program that reads two lines from the console and prints their concatenation.
  2. Modify the example above to read lines from a file instead of the console.
  3. Write a program that reads a line from the console, reverses it, and prints the result.
  4. Write a program that counts the number of lines in a given text file.
  5. Write a program that takes user input for two words and prints their concatenation after reading them separately (one word per line).
  6. Write a program that reads multiple lines from the console, removes any empty lines, and stores the remaining lines in an array.
  7. Write a program that reads a line from a file, splits it into words, sorts the words alphabetically, and prints the sorted list.
  8. Write a program that reads a line from the console or a file (user choice), reverses the line, and checks if the reversed line is a palindrome.
  9. Write a program that reads lines from a file, removes any lines containing specific words, and writes the filtered lines to another file.
  10. Write a program that reads a line from the console or a file (user choice), counts the number of vowels in the line, and prints the count.

FAQ

  1. Why do I need to consume the newline character after reading an integer?

After reading an integer using nextInt(), there's a remaining newline character in the input stream that needs to be consumed before reading the next line. If you don't consume it, subsequent calls to nextLine() will return an empty string until the user enters another line.

  1. Can I use nextLine() to read only the next word instead of a whole line?

No, the nextLine() method reads the entire line up to the newline character (\n). If you want to read individual words, you can split the line using the split() method.

  1. How do I close the Scanner object when I'm done with it?

You can call the close() method on the Scanner object to release any system resources it may be holding:

scanner.close();
  1. Why does my program hang after reading a line using nextLine()?

If your program is hanging, it's likely that there's an unconsumed newline character in the input stream. Make sure to consume any remaining newline characters after reading integers or other types that don't require them.

  1. Is it possible to read from multiple sources (console and file) simultaneously using a single Scanner object?

No, you should create separate Scanner objects for console input and file reading, as reading from multiple sources simultaneously may lead to unexpected behavior.

  1. What happens when I close the Scanner object that was used for console input?

Closing the Scanner object for console input will prevent further user input. If you need to read user input later in your program, create a new Scanner object for console input.

  1. How can I handle cases where the file being read does not exist or is not accessible?

You can use try-catch blocks around your file reading operations to gracefully handle exceptions such as FileNotFoundException and IOException:

try {
// Read from the file here
} catch (FileNotFoundException e) {
System.err.println("The specified file does not exist.");
} catch (IOException e) {
System.err.println("An error occurred while reading from the file.");
}
String nextLine() (Java) | Java | XQA Learn