# 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.

```plaintext
import java.util.Scanner;
```

---

### 📌 Step 2: Create Scanner Object

This connects Java program with **keyboard (**[**System.in**](http://System.in)**)**

```plaintext
Scanner sc = new Scanner(System.in);
```

* `Scanner` → class
    
* `sc` → object
    
* [`System.in`](http://System.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

```plaintext
int x = sc.nextInt();
```

✔ Reads an integer  
✔ Stops at space or enter

---

### 🔹 Example 2: String Input (single word)

```plaintext
String name = sc.next();
```

✔ Reads only **one word**

---

### 🔹 Example 3: String Input (full sentence)

```plaintext
String line = sc.nextLine();
```

✔ Reads **entire line including spaces**

---

## ⚠️ VERY IMPORTANT (Buffer Problem)

### ❓ Problem:

```plaintext
int age = sc.nextInt();
String name = sc.nextLine();  // ❌ skipped
```

### ❓ Why?

* `nextInt()` leaves **ENTER (**`\n`) in buffer
    
* `nextLine()` reads that ENTER and skips input
    

---

### ✅ Solution:

Add **one extra** `nextLine()`

```plaintext
int age = sc.nextInt();
sc.nextLine();   // clear buffer
String name = sc.nextLine();
```

---

## ✅ Complete Proper Program

```plaintext
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);
    }
}
```
