Skip to content
C

User Input

User input means allowing a program to receive data typed by the person using it, instead of using only fixed, hardcoded values. Java commonly uses the Scanner class to read this input from the keyboard.


1. What is User Input in Java?

User input means allowing a program to receive data typed by the person using it, instead of using only fixed, hardcoded values. Java commonly uses the Scanner class to read this input from the keyboard.

2. Why is it used?

Real applications must react to whatever the user types — a login form needs the username typed by the user, and a calculator app needs the numbers the user enters. Without user input, programs could only ever work with fixed values.

3. Real-Life Example

Think of a food delivery app asking you to type your address and choose your food items. The app can't know these details in advance — it must take them as input directly from you, the user.

4. Syntax

java
import java.util.Scanner; Scanner sc = new Scanner(System.in); int number = sc.nextInt(); String text = sc.nextLine();

5. Example Program

java
import java.util.Scanner; public class UserInputDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your age: "); int age = sc.nextInt(); System.out.println("Your age is: " + age); } }

Output:

Enter your age: 22
Your age is: 22

6. Key Points to Remember

  • Scanner requires importing java.util.Scanner at the top of the file.
  • Mixing nextInt() and nextLine() without care often causes a common beginner bug, since nextInt() leaves a leftover newline character behind.
  • Always close the Scanner object (sc.close()) once you're done reading input, in real projects.

Mock Test

  • User Input - Quick Test

    10 questions on reading keyboard input with the Scanner class.

    10 questions · 10 min · Easy
    Start Mock Test

Coding Problems