Nearby lessons

15 of 125

Java - User Input (Scanner)

📌 What You Will Learn
  • What a stream is and how data flows
  • Byte streams vs character streams
  • Reading and writing text files easily
  • The modern File methods and Scanner input
  • Serialization — saving an object to a file

User Input (Scanner) is a core concept of the Java language. This lesson explains Reading Input from the Keyboard with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Reading Input from the Keyboard

Old way — BufferedReader

Modern easy way — Scanner (Java 5+)

The Scanner class is much simpler. It can read words, whole lines, and numbers directly.

Example01
JCode Cell
1BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
2String name = br.readLine();
3int age = Integer.parseInt(br.readLine()); // convert String to int

Reading Input from the Keyboard

Trainer's Note: Trainer tip: nextLine() reads a whole line, next() reads only one word, nextInt() reads an int, nextDouble() reads a decimal. The Scanner is what most beginners and college projects use today.
Example02
JCode Cell
1import java.util.Scanner;
2 
3class ScannerDemo {
4 public static void main(String[] args) {
5 Scanner sc = new Scanner(System.in);
6 
7 System.out.print("Enter your name: ");
8 String name = sc.nextLine();
9 
10 System.out.print("Enter your age: ");
11 int age = sc.nextInt();
12 
13 System.out.println("Hello " + name + ", age " + age);
14 sc.close();
15 }
16}
Output
Enter your name: Rahul Enter your age: 20 Hello Rahul, age 20
📝 Key Takeaways
  • A stream is a flow of data: input brings data in, output sends it out.
  • Byte streams (InputStream/OutputStream) for images/videos; character streams (Reader/Writer) for text.
  • Wrap FileReader in BufferedReader to read text line by line.
  • Scanner is the simplest way to read input from the keyboard.
  • The File class gives file information; it does not read data.
  • Serialization saves objects to files; transient fields are not saved.
  • Always close streams — or better, use try-with-resources.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1