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

Java Scanner Class

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;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner("42 3.14");
		int whole = sc.nextInt();
		double decimal = sc.nextDouble();
		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;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner("42");
		if (sc.hasNextInt()) {
			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
	}
}
🔒

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.