← Back to Chapters

Java User Input using Scanner

⌨️ Java User Input using Scanner

? Quick Overview

In Java, user input from the keyboard is commonly handled using the Scanner class. It allows programs to read numbers, text, and other data types interactively.

? Key Concepts

  • Scanner is part of java.util package
  • Reads input from different sources (keyboard, files, etc.)
  • System.in represents standard input (keyboard)
  • Different methods are used for different data types

? Syntax / Theory

To use Scanner, you must import it and create an object linked to System.in. Each method reads a specific type of input.

  • nextInt() → integer input
  • nextDouble() → decimal input
  • next() → single word
  • nextLine() → full line of text

? Code Example(s)

? View Code Example
// Import Scanner class for user input
import java.util.Scanner;

class UserInputExample {
public static void main(String[] args) {

// Create Scanner object to read input from keyboard
Scanner sc = new Scanner(System.in);

// Ask user for their name
System.out.print("Enter your name: ");
String name = sc.nextLine();

// Ask user for their age
System.out.print("Enter your age: ");
int age = sc.nextInt();

// Display the entered data
System.out.println("Name: " + name);
System.out.println("Age: " + age);

// Close the scanner to free resources
sc.close();
}
}

? Live Output / Explanation

Output Example

Enter your name: Rahul
Enter your age: 21

Name: Rahul
Age: 21

The program pauses execution until the user provides input. Each Scanner method waits for the correct type of value.

? Interactive Simulator
Java HotSpot(TM) 64-Bit Server VM... Enter your name:
User Input >

✅ Tips & Best Practices

  • Always import java.util.Scanner
  • Close the Scanner after use to avoid resource leaks
  • Use nextLine() carefully after numeric input
  • Validate input in real applications

? Try It Yourself

  • Modify the program to take marks of a student
  • Read a double value for salary
  • Create a calculator using user input