← Back to Core Java Course | Chapter 2: Input & Output | Lesson 3 of 6

Java Scanner Class

Scanner lets your program read what a person types, like a teacher asking a question and writing down your answer. You can read words, numbers and more.
Syntax
java
import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
int number = scanner.nextInt();

What is Scanner?

Scanner, from java.util, wraps an input source -- typically System.in for keyboard input, but it can just as easily read from a file -- and gives you convenient methods to pull out words, lines, or numbers.

Example: What is Scanner?

java
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner("25 apples"); // wraps a source; System.in is typical, this is a hardcoded stand-in
		System.out.println(sc.nextInt() + " " + sc.next());
	}
}

Reading Strings

next() reads input up to the next whitespace, so it stops at the first space in a name like 'John Smith'; nextLine() instead reads everything up to the newline, capturing the full line including spaces.

Example: Reading Strings

java
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner("John Smith");
		System.out.println(sc.next());     // stops at the first space: "John"
		Scanner sc2 = new Scanner("John Smith");
		System.out.println(sc2.nextLine()); // reads the whole line: "John Smith"
	}
}

Reading Numbers

Methods like nextInt() and nextDouble() parse the next token as that specific numeric type and throw an InputMismatchException if what's typed doesn't actually look like a number.

Example: Reading Numbers

java
// Import java.util.Scanner so it can be used by its short name
import java.util.Scanner;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new Scanner object and store it in sc
		Scanner sc = new Scanner("42 3.14");
		// Declare whole and set it to sc.nextInt()
		int whole = sc.nextInt();
		// Declare decimal and set it to sc.nextDouble()
		double decimal = sc.nextDouble();
		// Print a line to the console
		System.out.println(whole + " " + decimal);
	}
}

Checking for Inputs

Calling hasNextInt() before nextInt() lets you check whether the next token is actually a valid integer first, which is the standard way to validate user input without crashing on bad data.

Example: Checking for Inputs

java
// Import java.util.Scanner so it can be used by its short name
import java.util.Scanner;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) {
		// Create a new Scanner object and store it in sc
		Scanner sc = new Scanner("42");
		// Check whether sc.hasNextInt()
		if (sc.hasNextInt()) {
			// Print a line to the console
			System.out.println("Valid int: " + sc.nextInt());
		}
	}
}

Closing the Scanner

Scanner holds an open connection to its input source, so calling close() when you're done frees that underlying resource -- skipping this rarely causes visible problems for console input, but it's a resource leak for file-backed Scanners.

Example: Closing the Scanner

java
import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner("done");
		System.out.println(sc.next());
		sc.close(); // frees the underlying resource
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Reading a number with nextInt() and then nextLine(), which returns an empty string because the newline is still in the buffer.
  2. Calling nextInt() when the user types text, which throws InputMismatchException.
  3. Calling next() when no input is left, which throws NoSuchElementException; check hasNext().
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.