Java Scanner — Free Java Tutorial
Learn Java Scanner in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn Java Scanner in Java with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
Java Scanner in Java
The Scanner class (java.util.Scanner) reads input from various sources: System.in (keyboard), files, or strings. It is the standard way to read user input in console Java programs.
Import it with: import java.util.Scanner; Then create an instance: Scanner sc = new Scanner(System.in);
Key methods: nextInt(), nextDouble(), nextLong(), next() (reads one word), nextLine() (reads entire line including spaces).
Always close the Scanner when done: sc.close(). This releases the underlying stream resource.
Common pitfall: after calling nextInt() or nextDouble(), a newline character remains in the buffer. Call sc.nextLine() to consume it before calling nextLine() again.
Java Scanner — Syntax
import java.util.Scanner; Scanner sc = new Scanner(System.in); int n = sc.nextInt(); // read integer double d = sc.nextDouble(); // read decimal String word = sc.next(); // read one word String line = sc.nextLine(); // read full line sc.close();
Learn Java Scanner step by step with Syllab's free interactive Java tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Java course →