Input in Java
Introduction
Java allows programs to receive input from users during execution. For this, we use the Scanner class from the java.util package.
What is System.in?
- System.in is a standard input stream.
- It reads raw bytes from the keyboard.
- It’s usually wrapped inside a Scanner object to read formatted input (text, numbers, etc.).
Steps to Take Input Using Scanner
-
Import the Scanner class
import java.util.Scanner; -
Create a Scanner object
Scanner sc = new Scanner(System.in); -
Use Scanner methods to read input
int age = sc.nextInt(); String name = sc.nextLine();
Example: Input Name, Age, and Course
import java.util.Scanner;
public class InputOutputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your age: ");
int age = sc.nextInt();
sc.nextLine(); // Consume leftover newline
System.out.print("Enter the course you're interested in: ");
String course = sc.nextLine();
System.out.println("Welcome " + name + ", you are " + age +
" years old, and you have successfully enrolled in the "
+ course + " course at Shiksha Sanchar.");
}
}
Sample Input:
Enter your name: Devanshi
Enter your age: 21
Enter the course you're interested in: Java
Output:
Welcome Devanshi, you are 21 years old, and you have successfully enrolled in the Java course at Shiksha Sanchar.
Why nextLine() after nextInt() ?
After using nextInt(), a newline character is left in the input buffer. So, before using nextLine(), we call it once to consume that leftover newline.
Common Scanner Methods
| Method | Purpose | Example |
|---|---|---|
| nextInt() | Read integer input | int num = sc.nextInt(); |
| nextFloat() | Read float input | float f = sc.nextFloat(); |
| nextDouble() | Read double input | double d = sc.nextDouble(); |
| next() | Read a single word (no spaces) | String s = sc.next(); |
| nextLine() | Read entire line (with spaces) | String line = sc.nextLine(); |
| nextBoolean() | Read boolean input (true/false) | boolean b = sc.nextBoolean(); |
Summary:
| Concept | Description |
|---|---|
| System.in | Standard input stream from the keyboard |
| Scanner class | Helps to read user input easily |
| import java.util.Scanner; | Required to use the Scanner class |
| nextLine() | Reads entire line with spaces |
| nextInt() | Reads an integer |
| sc.nextLine() hack | Used after nextInt() to consume leftover newline |