Skip to main content

Command Palette

Search for a command to run...

input in java

Published
โ€ข2 min readโ€ขView as Markdown

๐Ÿ“ฅ 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 โ†’ class

  • sc โ†’ object

  • System.in โ†’ standard input (keyboard)


๐Ÿ“Œ Step 3: Take Input Using Methods

Data TypeMethod
intnextInt()
floatnextFloat()
doublenextDouble()
wordnext()
full linenextLine()
charnext().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 buffer

  • nextLine() 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);
    }
}