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
javaimport java.util.Scanner; Scanner sc = new Scanner(System.in); int number = sc.nextInt(); String text = sc.nextLine();
5. Example Program
javaimport 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: 226. Key Points to Remember
Scannerrequires importingjava.util.Scannerat the top of the file.- Mixing
nextInt()andnextLine()without care often causes a common beginner bug, sincenextInt()leaves a leftover newline character behind. - Always close the
Scannerobject (sc.close()) once you're done reading input, in real projects.