Codectionary / Developer documentation / Java

Scanner (User Input)

The Scanner class, from java.util, reads input from various sources - most commonly System.in for keyboard input from the console. It provides typed methods like nextInt(), nextDouble(), and nextLine() to read and parse input directly into the desired type, avoiding manual string conversion. Scanner must be imported explicitly since it's not part of java.lang.

Syntax

Scanner scanner = new Scanner(System.in);

Examples

Reading Basic Input

Reading a line of text and a number from the console.

import java.util.Scanner;

public class InputExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        System.out.println("Hello " + name + ", you are " + age + " years old");
        scanner.close();
    }
}

Reading Multiple Value Types

Using the type-specific methods Scanner provides for cleaner parsing.

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a price: ");
double price = scanner.nextDouble();

System.out.print("Are you a member? (true/false): ");
boolean isMember = scanner.nextBoolean();

double finalPrice = isMember ? price * 0.9 : price;
System.out.println("Final price: " + finalPrice);

Input Validation Loop

Repeating a prompt until valid input is provided, using hasNextInt() to check before reading.

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
int number = 0;
boolean valid = false;

while (!valid) {
    System.out.print("Enter a whole number: ");
    if (scanner.hasNextInt()) {
        number = scanner.nextInt();
        valid = true;
    } else {
        System.out.println("That's not a valid number, try again");
        scanner.next();  // discard the invalid token
    }
}

System.out.println("You entered: " + number);

Best practices

  • Always close the Scanner when done (scanner.close()) to release the underlying resource, especially in larger applications
  • Be careful mixing nextInt()/nextDouble() with nextLine() - the numeric methods don't consume the trailing newline, which can cause an empty read on the next nextLine() call
  • Use hasNextInt(), hasNextDouble(), etc. to validate input before attempting to read it, avoiding an InputMismatchException
  • Create one Scanner instance for System.in per program rather than opening multiple - reusing the same instance avoids resource conflicts

At a glance

Purpose
General-purpose application development
File extension
.java
Runs in
Java Virtual Machine
Usually used with
JDK and Java libraries

Specifications & further reading

Related Java documentation

Variables & Primitive Data Types
Java is a statically-typed language, meaning every variable must be declared with an explicit type before use, and that type cannot change afterward. Java has eight primitive types - byte, short, int, long, float, double, char, and boolean - which store simple values directly rather than references, making them fast and memory-efficient. Anything beyond primitives (String, arrays, custom classes) is a reference type instead.
System.out.println / print / printf
System.out is Java's standard output stream, and it exposes three main methods for writing text to the console. println() prints its argument followed by a newline, print() prints without adding a newline, and printf() gives C-style formatted output using format specifiers like %d, %s, and %.2f for precise control over how values are displayed.
Comments & Javadoc
Java supports single-line comments with //, multi-line comments with /* */, and a special documentation format called Javadoc, written as /** */. Javadoc comments support tags like @param, @return, and @throws, and can be processed by the javadoc tool to automatically generate HTML API documentation - the same format used for Java's own official standard library docs.
Arithmetic & Assignment Operators
Java provides the standard arithmetic operators for numeric computation: +, -, *, / for division, and % for the remainder (modulus). It also has compound assignment operators (+=, -=, etc.) that combine an operation with assignment, along with increment (++) and decrement (--) operators in both prefix and postfix forms, which subtly differ in when the value is updated relative to being used.