Input and Output in Java
Reading from the keyboard and writing to the console, with the Scanner pitfall that catches almost every beginner.
-
Java Basics
- Introduction to Java
- Setting Up Java and Writing Your First Program
- Variables, Data Types and Literals in Java
- Type Casting and Type Conversion in Java
- Operators and Expressions in Java
- Input and Output in Java
- Comments, Keywords and Naming Conventions in Java
- Control Flow in Java: if, else and switch
- Loops in Java: for, while and do-while
- Methods
- Arrays and Strings
-
OOP
- Classes and Objects in Java
- Constructors in Java
- The this Keyword in Java
- The static Keyword in Java
- Encapsulation in Java
- Access Modifiers in Java
- Inheritance in Java
- Method Overriding and super in Java
- Polymorphism in Java
- Abstraction, Abstract Classes and Interfaces in Java
- Composition, Aggregation and Association in Java
- The Object Lifecycle in Java
- Core Java
- Exception Handling
-
Collections
- The Java Collections Framework
- List in Java: ArrayList, LinkedList, Vector and Stack
- Set in Java: HashSet, LinkedHashSet and TreeSet
- Map in Java: HashMap, LinkedHashMap and TreeMap
- How HashMap Works Internally in Java
- Queue and Deque in Java: ArrayDeque and PriorityQueue
- Iterators in Java
- Comparable and Comparator in Java
- Collections Utilities and Choosing the Right Collection
- Generics
- Java 8+
- Stream API
- Date and Time
- File and I/O
-
Multithreading
- Threads in Java: Processes, Runnable and Thread
- Thread Lifecycle in Java
- Synchronization in Java: synchronized and volatile
- Locks and Atomic Classes in Java
- Race Conditions and Deadlocks in Java
- The Executor Framework and Thread Pools in Java
- Future and CompletableFuture in Java
- Concurrent Collections in Java
- The Java Memory Model
- JVM and Memory
- Advanced Java
- Networking
- JDBC
- Testing
Writing output
System.out.print("No line break. ");
System.out.println("With a line break.");
System.out.printf("%s scored %d marks (%.2f%%)%n", "Ravi", 87, 87.0);| Format | Meaning |
|---|---|
%s | Any value, converted with toString |
%d | Whole number |
%f | Decimal, %.2f for two places |
%n | Platform line separator, preferred over a literal newline |
%% | A literal percent sign |
System.err writes to the error stream. Keep diagnostics there so ordinary output stays clean when it is redirected.
Reading input with Scanner
import java.util.Scanner;
public class Enrolment {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Name: ");
String name = in.nextLine();
System.out.print("Age: ");
int age = in.nextInt();
System.out.printf("%s is %d years old.%n", name, age);
}
}The nextInt then nextLine trap
This is the single most common beginner bug in Java input.
int age = in.nextInt(); // reads the digits, leaves the line break behind
String city = in.nextLine(); // consumes that leftover break, returns ""nextInt stops at the end of the number and does not consume the line break that follows it. The next nextLine therefore reads an empty remainder. Two reliable fixes:
// Option 1: consume the rest of the line explicitly
int age = in.nextInt();
in.nextLine();
String city = in.nextLine();
// Option 2: read every line as text and convert yourself
int age = Integer.parseInt(in.nextLine().trim());
String city = in.nextLine();The second option is more predictable and is the habit worth forming.
Validating input
Scanner in = new Scanner(System.in);
int quantity;
while (true) {
System.out.print("Quantity: ");
String line = in.nextLine().trim();
try {
quantity = Integer.parseInt(line);
if (quantity > 0) {
break;
}
System.out.println("Please enter a positive number.");
} catch (NumberFormatException e) {
System.out.println("That is not a whole number.");
}
}Reading with BufferedReader
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BulkInput {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
int lines = 0;
while ((line = reader.readLine()) != null && !line.isBlank()) {
lines++;
}
System.out.println("Lines read: " + lines);
}
}Scanner compared with BufferedReader
| Aspect | Scanner | BufferedReader |
|---|---|---|
| Parsing | Built in, token by token | Text only, parse yourself |
| Speed | Slower | Faster for large input |
| Checked exceptions | None to handle | IOException must be handled |
| Best for | Small interactive programs | Bulk input |
Common mistakes
- Mixing
nextIntandnextLinewithout accounting for the leftover line break. - Creating several
Scannerobjects overSystem.in. One is enough, and buffering makes extras unreliable. - Closing a
Scannerwrapped aroundSystem.in, which closes standard input for the rest of the program. - Assuming input is well formed and letting
InputMismatchExceptionend the program.
Best practices
- Read whole lines and convert them yourself. It removes an entire class of bug.
- Validate at the boundary and loop until the value is acceptable.
- Use
printfwhen output alignment matters.
Practice
- Write a program that reads a name and three marks and prints the average to two decimal places.
- Explain, in terms of the input buffer, why a
nextLineafternextIntcan return an empty string. - Convert a
Scannerbased reader into aBufferedReaderbased one and state which exception you now have to handle.
Conclusion
Console input is simple once you accept that a Scanner reads tokens, not lines. Read lines, parse deliberately, and validate before using the value.