input in java
๐ฅ Taking Input in Java (Proper Explanation)
In Java, input means taking data from the user at runtime (keyboard).
Java does NOT take input automatically.
We must explicitly tell Java how to read input.
๐น Why do we need input classes?
Java is a strongly typed & secure language, so it uses classes to read input safely.
The most commonly used class is:
โ Scanner
โ 1๏ธโฃ Scanner Class (Best for Beginners)
๐ Step 1: Import Scanner
Java libraries are not loaded automatically.
import java.util.Scanner;
๐ Step 2: Create Scanner Object
This connects Java program with keyboard (System.in)
Scanner sc = new Scanner(System.in);
Scannerโ classscโ objectSystem.inโ standard input (keyboard)
๐ Step 3: Take Input Using Methods
| Data Type | Method |
| int | nextInt() |
| float | nextFloat() |
| double | nextDouble() |
| word | next() |
| full line | nextLine() |
| char | next().charAt(0) |
๐น Example 1: Integer Input
int x = sc.nextInt();
โ Reads an integer
โ Stops at space or enter
๐น Example 2: String Input (single word)
String name = sc.next();
โ Reads only one word
๐น Example 3: String Input (full sentence)
String line = sc.nextLine();
โ Reads entire line including spaces
โ ๏ธ VERY IMPORTANT (Buffer Problem)
โ Problem:
int age = sc.nextInt();
String name = sc.nextLine(); // โ skipped
โ Why?
nextInt()leaves ENTER (\n) in buffernextLine()reads that ENTER and skips input
โ Solution:
Add one extra nextLine()
int age = sc.nextInt();
sc.nextLine(); // clear buffer
String name = sc.nextLine();
โ Complete Proper Program
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter age: ");
int age = sc.nextInt();
sc.nextLine(); // buffer clear
System.out.print("Enter name: ");
String name = sc.nextLine();
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
}