Java for Beginners · Module 2: Building Blocks
🎯 Why Do We Need Input?
A program that always prints the same answer is not very useful. Real programs ask the user for data: a name, a marks list, an amount. In Java, the easiest way to read keyboard input is the Scanner class.
1️⃣ The Three Steps to Use Scanner
you type: 19 ⏎
raw bytes
turns text into int, double, String
int age = 19
Figure 1: How Scanner turns keyboard input into values.
- Import it:
import java.util.Scanner;at the top of the file. - Create it:
Scanner sc = new Scanner(System.in); - Read with it:
sc.nextInt(),sc.nextDouble(),sc.nextLine()and so on.
Here System.in means “the keyboard”. It is the input partner of System.out, which means “the screen”.
2️⃣ Scanner Methods
| Method | Reads | Stops at |
nextInt() | an int | whitespace |
nextLong() | a long | whitespace |
nextDouble() | a double | whitespace |
nextBoolean() | true or false | whitespace |
next() | one word (String) | whitespace |
nextLine() | the whole line (String) | Enter key |
Figure 2: The Scanner methods you will use most.
Program 1: Read a name, age and CGPA
import java.util.Scanner;
public class ReadBasics {
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();
System.out.print("Enter your CGPA: ");
double cgpa = sc.nextDouble();
System.out.println("Name : " + name);
System.out.println("Age : " + age);
System.out.println("CGPA : " + cgpa);
sc.close();
}
}
Enter your name: Ajay Dabade
Enter your age: 19
Enter your CGPA: 8.75
Name : Ajay Dabade
Age : 19
CGPA : 8.75
- Use
print(notprintln) for the prompt so the cursor stays on the same line. nextLine()reads the full name, including the space.nextInt()andnextDouble()read the number and convert it for you. No parsing is needed.sc.close()releases the keyboard when you are done.
3️⃣ Reading Several Numbers
Numbers can be typed on one line separated by spaces, or on different lines. Scanner treats spaces and Enter the same way when reading numbers.
import java.util.Scanner;
public class SumOfThree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int sum = a + b + c;
double avg = sum / 3.0;
System.out.println("Sum = " + sum);
System.out.printf("Average = %.2f%n", avg);
}
}
Enter three numbers: 10 20 30
Sum = 60
Average = 20.00
- Each
nextInt()picks the next number and skips the spaces. sum / 3.0uses a decimal divisor, so the average keeps its fraction (see Lesson 9).
4️⃣ The Newline Trap: nextInt() then nextLine()
This is the most common Scanner bug. nextInt() reads only the digits and leaves the Enter key (the newline) waiting in the buffer. A following nextLine() reads that leftover and returns an empty String.
19⏎Rahul⏎nextInt() takes 19leaves ⏎ behind
nextLine() reads up to that ⏎gets an empty String
nextLine() after nextInt() to throw away the leftover Enter.Figure 3: The leftover newline trap.
Program 2: The bug
import java.util.Scanner;
public class NewlineTrap {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Age: ");
int age = sc.nextInt();
System.out.print("Name: ");
String name = sc.nextLine();
System.out.println("Age = " + age + ", Name = [" + name + "]");
}
}
Age: 19
Name: Age = 19, Name = []
Program 3: The fix
import java.util.Scanner;
public class NewlineFix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Age: ");
int age = sc.nextInt();
sc.nextLine(); // consume the leftover Enter
System.out.print("Name: ");
String name = sc.nextLine();
System.out.println("Age = " + age + ", Name = [" + name + "]");
}
}
Age: 19
Name: Rahul
Age = 19, Name = [Rahul]
- The square brackets in the output make the empty name easy to see.
- The extra
sc.nextLine();simply throws the leftover Enter away. This is needed whenevernextLine()followsnextInt(),nextDouble()ornext().
5️⃣ Checking Before You Read
If the user types letters where a number is expected, nextInt() fails. The hasNextInt() method checks first and returns true or false, without reading anything.
import java.util.Scanner;
public class ValidInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your age: ");
if (sc.hasNextInt()) {
int age = sc.nextInt();
System.out.println("Age accepted: " + age);
} else {
System.out.println("That is not a whole number: " + sc.next());
}
}
}
Run 1:
Enter your age: 21
Age accepted: 21
Run 2:
Enter your age: abc
That is not a whole number: abc
- The
ifstatement is covered in Lesson 16. For now, read it as “if the next item is an int, read it; otherwise report the problem”. - The
elsebranch usesnext()to read and show the bad word.
6️⃣ Errors Beginners Meet
Forgetting the import
public class NoImport {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(n);
}
}
NoImport.java:3: error: cannot find symbol
Scanner sc = new Scanner(System.in);
^
symbol: class Scanner
location: class NoImport
NoImport.java:3: error: cannot find symbol
Scanner sc = new Scanner(System.in);
^
symbol: class Scanner
location: class NoImport
2 errors
- Java does not know where
Scannerlives. Addimport java.util.Scanner;at the top. The error appears twice because the name is used twice on that line.
Typing the wrong kind of value
import java.util.Scanner;
public class BadInput {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(n);
}
}
abc
Exception in thread “main” java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:947)
at java.base/java.util.Scanner.next(Scanner.java:1602)
at java.base/java.util.Scanner.nextInt(Scanner.java:2267)
at java.base/java.util.Scanner.nextInt(Scanner.java:2221)
at BadInput.main(BadInput.java:6)
- The program compiles, but crashes when the user types letters for an int. Use
hasNextInt()to check first, or handle the error with exceptions (Lesson 28).
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Missing import java.util.Scanner; | cannot find symbol | Add the import |
nextLine() right after nextInt() | Reads an empty String | Add an extra nextLine() |
Using next() to read a full name | Stops at the first space | Use nextLine() |
| Creating a new Scanner for every read | Wasteful and can lose input | Create one Scanner and reuse it |
Prompt with println | Input starts on the next line | Use print |
Reading a char with nextChar() | No such method | Use sc.next().charAt(0) |
❓ Frequently Asked Questions
Q1. Why do we write System.in?
It tells Scanner to read from the keyboard. A file or a String could be given instead.
Q2. Do I have to call close()?
It is good practice, and it releases the resource. In small programs forgetting it does no harm, but never close a Scanner on System.in if you still need to read from the keyboard later.
Q3. How do I read a single character?
Scanner has no nextChar(). Read a word and take its first letter: char c = sc.next().charAt(0);
Q4. Is there another way to read input?
Yes, BufferedReader is faster for large inputs and is used in competitive programming. Scanner is simpler for learning.
✅ Key Takeaways
- Import
java.util.Scanner, createnew Scanner(System.in), then call its methods. nextInt(),nextDouble(),next()stop at whitespace.nextLine()reads the whole line.- After
nextInt()ornextDouble(), add an extranextLine()before reading a full line. - Use
hasNextInt()to check input before reading it. - Typing the wrong kind of value causes
InputMismatchException.
🎓 Practice questions: (1) Write a program that reads two numbers and prints their sum, difference and product. (2) Read a student’s name and three subject marks, then print the total and percentage. (3) Why doesnextLine()return an empty String afternextInt()? (4) How would you read a single character from the keyboard? (5) Write a program that reads the radius of a circle and prints its area usingMath.PI.
All 30 lessons in this series (open course page)
Module 1 · Getting Started
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java