Taking Input with Scanner in Java
Scanner, from java.util, is the standard beginner-friendly way to read input in Java. Creating one wraps System.in — the program's standard input stream — and its methods like nextInt(), nextDouble(), and nextLine() each read and parse the next token as a specific type, blocking until the user actually types something and presses enter.
Mixing nextInt() or nextDouble() with nextLine() is the single most common Scanner gotcha. The numeric methods only consume the number itself, leaving the trailing newline in the buffer — so a nextLine() called right after can immediately (and unexpectedly) return an empty string, unless that leftover newline is explicitly consumed first.
Create a Scanner
new Scanner(System.in) wraps standard input so its methods can read whatever the user types.
Read a specific type
nextInt(), nextDouble(), and nextBoolean() each read the next token and parse it as that type, throwing an exception if it doesn't match.
Read a full line
nextLine() reads everything up to the next newline, including spaces, unlike the type-specific methods which stop at whitespace.
The newline gotcha
nextInt() leaves the newline after the number in the buffer, so a nextLine() called right after can return an unexpectedly empty string.
Close it when done
Calling close() releases the underlying resource, which matters more for file or network sources than for System.in, but is still good practice.
import java.util.Scanner; public class InputDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your age: "); int age = scanner.nextInt(); System.out.println("You are " + age + " years old."); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.