Back to Java
2026-04-055 min read

next() (Java)

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

Why This Matters

Welcome to this in-depth guide on the next() method in Java's Scanner class! This tutorial is designed to help you understand its importance, master its usage, and avoid common pitfalls.

Why This Matters

The next() method plays a crucial role when reading input from the user or a file using the Scanner class in Java. It allows you to read the next token (a sequence of characters that is delimited by white spaces) from the input stream. Understanding and effectively utilizing this method will help you write cleaner, more efficient code, especially during interviews, real-world programming tasks, or debugging common issues.

Prerequisites

To fully grasp this lesson, you should be familiar with the following:

  1. Basic Java syntax and data types (e.g., int, double, String)
  2. Input/Output operations in Java using the Scanner class
  3. Concepts of tokens, white spaces, and delimiters in programming

Core Concept

Understanding next() Method

The next() method is a part of the Scanner class in Java that reads the next token from the input stream. It can be used to read primitive data types (e.g., int, double, boolean) and strings. By default, the delimiter for tokens is any combination of white spaces (space, tab, newline).

import java.util.Scanner;

public class NextMethodExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter three numbers separated by spaces: ");
int num1 = scanner.nextInt(); // Read the first number
double num2 = scanner.nextDouble(); // Read the second number
String num3 = scanner.next(); // Read the third number (up to the next white space)
System.out.println("You entered: " + num1 + ", " + num2 + ", and " + num3);
}
}

In this example, we read three numbers entered by the user separated by spaces using nextInt(), nextDouble(), and next(). The next() method reads a token up to the next white space.

Reading Lines with nextLine()

To read an entire line (including newline character), use the nextLine() method instead of next(). This method is particularly useful when reading strings that contain multiple words or when you want to read an entire line at once.

import java.util.Scanner;

public class NextLineExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String sentence = scanner.nextLine(); // Read an entire line (including newline character)
System.out.println("You entered: " + sentence);
}
}

In this example, we read an entire line using the nextLine() method and print it out.

Worked Example

Consider a simple program that reads two numbers from the user, calculates their sum, and prints the result.

import java.util.Scanner;

public class NextMethodWorkedExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = scanner.nextInt(); // Read the first number
System.out.print("Enter second number: ");
int num2 = scanner.nextInt(); // Read the second number
int sum = num1 + num2;
System.out.println("The sum of " + num1 + " and " + num2 + " is " + sum);
}
}

In this example, we read two numbers using nextInt() and calculate their sum. The program then prints the result to the console.

Common Mistakes

1. Reading a line after reading primitive data types

When you use nextLine() before nextInt(), the input buffer may still contain newline characters, causing subsequent calls to nextInt() to fail. To avoid this issue, always read a line after reading all primitive data types or use the useDelimiter() method to set a custom delimiter.

import java.util.Scanner;

public class NextMethodCommonMistakeExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\s+"); // Set custom delimiter to read all white spaces
System.out.print("Enter three numbers separated by spaces: ");
int num1 = scanner.nextInt(); // Read the first number
double num2 = scanner.nextDouble(); // Read the second number
String num3 = scanner.next(); // Read the third number (up to the next white space)
System.out.println("You entered: " + num1 + ", " + num2 + ", and " + num3);
}
}

In this example, we set a custom delimiter using useDelimiter() to read all white spaces, avoiding the issue of reading newline characters after primitive data types.

2. Forgetting to close the Scanner

Always remember to close the Scanner object when you're done with it to free up system resources.

import java.util.Scanner;

public class NextMethodCommonMistakeExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// ... read input and perform calculations
scanner.close(); // Close the Scanner object
}
}

In this example, we close the Scanner object after reading input to free up system resources.

Practice Questions

  1. Write a program that reads three integers from the user using nextInt(), calculates their average, and prints the result.
  2. Modify the worked example to read an integer and a string, concatenate them, and print the result.
  3. Write a program that reads a line containing two numbers separated by a comma (,), converts each number to its square root, and prints the result.
  4. Write a program that reads a line containing a student's name and score, validates the score (it should be between 0 and 100), and prints a message indicating whether the score is valid or invalid.

FAQ

Q: Can I use next() to read an entire line?

A: No, next() reads only up to the next white space. To read an entire line (including newline character), use nextLine().

Q: What happens if I forget to close the Scanner object?

A: If you forget to close the Scanner object, it may cause memory leaks and consume unnecessary system resources. Always remember to close the Scanner object when you're done with it.

Q: How can I read an entire line without consuming the newline character for further reading?

A: To read an entire line without consuming the newline character, use nextLine() and store the result in a String. Then, use next() or another nextLine() to consume the newline character.

Q: Can I set a custom delimiter for the Scanner?

A: Yes, you can set a custom delimiter using the useDelimiter() method. This allows you to read input based on your desired delimiters instead of the default white spaces.

next() (Java) | Java | XQA Learn