Chapter 5: Input and Output
1. Why Input & Output Matters
Until now, all our values were hardcoded (like int age = 25;). That’s fine for learning, but in real programs you want the user to enter their own data — name, age, marks, etc. And you want to show output in a pretty, formatted way — not just plain println.
Java gives us two main ways to read input from the user (keyboard):
- Scanner class → easiest and most popular for beginners
- BufferedReader → faster and more powerful (used in advanced/enterprise code)
We’ll learn both, but start with Scanner — you’ll use it 90% of the time.
2. Reading Input Using Scanner Class
Step 1: Import Scanner
|
0 1 2 3 4 5 6 |
import java.util.Scanner; |
Step 2: Create a Scanner object
|
0 1 2 3 4 5 6 |
Scanner sc = new Scanner(System.in); |
- System.in → means “read from keyboard”
Step 3: Read different types of input
| Method | What it reads | Example Code |
|---|---|---|
| nextInt() | Integer (whole number) | int age = sc.nextInt(); |
| nextDouble() | Decimal number | double salary = sc.nextDouble(); |
| nextFloat() | Float (less precise decimal) | float height = sc.nextFloat(); |
| next() | One word (until space) | String firstName = sc.next(); |
| nextLine() | Full line (including spaces) | String fullName = sc.nextLine(); |
| nextBoolean() | true or false | boolean isStudent = sc.nextBoolean(); |
Complete Example Program — Let’s make a fun “Personal Info Collector”
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import java.util.Scanner; public class InputDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your full name: "); String fullName = sc.nextLine(); // reads entire line System.out.print("Enter your age: "); int age = sc.nextInt(); System.out.print("Enter your height in meters (e.g. 1.75): "); double height = sc.nextDouble(); System.out.print("Are you from Mumbai? (true/false): "); boolean isFromMumbai = sc.nextBoolean(); // Consume the leftover newline character (very important!) sc.nextLine(); System.out.print("Enter your favorite quote: "); String quote = sc.nextLine(); // Now print everything System.out.println("\n=== Your Details ==="); System.out.println("Name : " + fullName); System.out.println("Age : " + age + " years"); System.out.println("Height : " + height + " m"); System.out.println("From Mumbai? : " + isFromMumbai); System.out.println("Favorite Quote: " + quote); sc.close(); // Good practice — close the scanner } } |
Important Tip — The nextLine() Trap (Common Mistake!)
After nextInt(), nextDouble(), etc., there is a leftover newline character (\n) in the input buffer. When you call nextLine() after that, it reads an empty line!
Solution: Add sc.nextLine(); right after reading numbers to consume the leftover \n.
Example of the problem:
|
0 1 2 3 4 5 6 7 |
int age = sc.nextInt(); // user types 25 + Enter String name = sc.nextLine(); // name becomes "" (empty!) — because it reads the leftover Enter |
Fix:
|
0 1 2 3 4 5 6 7 8 |
int age = sc.nextInt(); sc.nextLine(); // eat the leftover newline String name = sc.nextLine(); // now works perfectly |
3. Reading Input Using BufferedReader (Advanced Way)
This is older but faster and used in many real-world apps.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class BufferedReaderDemo { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter your name: "); String name = br.readLine(); System.out.print("Enter your age: "); int age = Integer.parseInt(br.readLine()); // convert String to int System.out.print("Enter your salary: "); double salary = Double.parseDouble(br.readLine()); System.out.println("Hello " + name + "! You are " + age + " years old and earn ₹" + salary); } } |
Pros of BufferedReader:
- Faster for large input
- Reads everything as String → you convert manually
Cons:
- More code
- Need to handle IOException
For now → use Scanner — it’s perfect for beginners and most college/projects.
4. Beautiful Output Formatting
Java gives you two powerful ways to print nicely formatted output:
A. System.out.println() and print() (Basic)
You already know these — but you can make them pretty with concatenation and escape sequences:
|
0 1 2 3 4 5 6 7 8 9 |
System.out.println("Name: " + name); System.out.println("Age : " + age + " years"); System.out.println("\tHeight: " + height + " m"); // \t = tab System.out.println("Quote: \"" + quote + "\""); // \" = print double quotes |
B. printf() — The Professional Way (like C language)
printf = print formatted
Syntax:
|
0 1 2 3 4 5 6 |
System.out.printf("format string", value1, value2, ...); |
Common Format Specifiers:
| Specifier | Meaning | Example | Output |
|---|---|---|---|
| %d | Integer (whole number) | %d | 25 |
| %f | Floating point (decimal) | %.2f (2 decimal places) | 85.50 |
| %s | String | %s | Webliance |
| %c | Character | %c | A |
| %b | Boolean | %b | true |
| %% | Print % sign | %% | % |
| \n | New line |
Real Example — Beautiful Bill Receipt
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class PrintfDemo { public static void main(String[] args) { String item = "Laptop"; int qty = 1; double price = 85999.99; double discount = 10.0; double finalPrice = price * (1 - discount/100); System.out.println("====================================="); System.out.printf(" INVOICE - Webliance Shop \n"); System.out.println("====================================="); System.out.printf("%-15s : %d pcs\n", "Item", qty); System.out.printf("%-15s : ₹%,.2f\n", "Unit Price", price); System.out.printf("%-15s : %.1f%%\n", "Discount", discount); System.out.printf("%-15s : ₹%,.2f\n", "Final Amount", finalPrice); System.out.println("====================================="); System.out.println("Thank you for shopping with us! 😊"); } } |
Output looks like this:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
===================================== INVOICE - Webliance Shop ===================================== Item : 1 pcs Unit Price : ₹85,999.99 Discount : 10.0% Final Amount : ₹77,399.99 ===================================== Thank you for shopping with us! 😊 |
Tips for printf:
- %-15s → left-align, width 15 characters
- %,.2f → add commas for thousands + 2 decimal places
Homework for You (Fun Practice!)
- Create a program called StudentInfo.java:
- Ask user: name (nextLine), roll number (nextInt), percentage (nextDouble), section (next — single char like ‘A’)
- Print everything in a beautiful formatted table using printf
- Make a Simple Calculator:
- Ask for two numbers
- Ask for operation (+, -, *, /)
- Show result with 2 decimal places
- Try the nextLine() trap intentionally — see what happens, then fix it!
You’re doing amazing! Now your programs can talk to users and look professional.
