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.
Scanner is part of java.util packageSystem.in represents standard input (keyboard)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 inputnextDouble() → decimal inputnext() → single wordnextLine() → full line of text
// 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();
}
}
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.
java.util.ScannernextLine() carefully after numeric input