Java User Input & Output: Complete Beginner Guide with Examples (2026)
⏱️ Reading Time: 20 minutes | 🎯 Difficulty: Beginner | 🔄 Last Updated: August 21, 2026
What is Input & Output in Java?
Input is data that flows into your program from an external source — typically the keyboard, a file, or a network connection.
Output is data that flows out of your program — displayed on the screen, saved to a file, or sent over a network.
Think of your Java program as a restaurant kitchen:
- Input = Raw ingredients coming from the supplier (user typing, file reading)
- Processing = The chef cooking (your Java logic)
- Output = The finished dish served to the customer (displayed result)
Without input, your program is a recipe with no ingredients. Without output, the customer never sees the dish.
1// Input: User types "Rahul" 2// Processing: Program stores and formats the name 3// Output: "Welcome, Rahul!"
Why Does User Input Matter?
"I built a calculator with hardcoded values. My mentor asked me to make it interactive. I realized I had learned syntax but not programming." — Every self-taught developer, eventually.
Static programs (with hardcoded values) are useful for learning, but real-world applications are interactive. Here is where user input becomes essential:
| Application | Input Needed | Output Produced |
|---|---|---|
| Banking App | Account number, PIN, transfer amount | Balance, transaction receipt |
| E-Commerce | Product name, quantity, address | Bill, order confirmation |
| Student Portal | Roll number, marks | Grade card, result status |
| Gaming | Key presses, mouse clicks | Score, game state |
| Chat Application | Message text | Chat history, notifications |
Java provides three primary ways to read keyboard input:
Scanner— Easy, versatile, beginner-friendlyBufferedReader— Fast, ideal for large text/competitive programmingConsole— Secure, perfect for password input
The Scanner Class
The Scanner class is the most popular way to read user input in Java. It lives in the java.util package and can parse primitive types and strings directly.
Syntax
1import java.util.Scanner; // Step 1: Import 2 3Scanner input = new Scanner(System.in); // Step 2: Create object 4// System.in = standard input stream (keyboard)
How It Works
Scanner reads a stream of characters and breaks it into tokens using whitespace (spaces, tabs, newlines) as delimiters. Each next...() method grabs the next token and converts it to the requested type.
1import java.util.Scanner; 2 3public class ScannerDemo { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 7 System.out.print("Enter your name: "); 8 String name = input.nextLine(); 9 10 System.out.println("Hello, " + name + "!"); 11 12 input.close(); // Always close when done! 13 } 14}
Sample Run:
1Enter your name: Rahul 2Hello, Rahul!
Reading Different Data Types
Scanner provides dedicated methods for every primitive type. Here is the complete reference:
Scanner Methods Table
| Method | Returns | Example Input | Notes |
|---|---|---|---|
next() | String | Hello | Reads one word (stops at space) |
nextLine() | String | Hello World | Reads entire line including spaces |
nextInt() | int | 25 | Throws InputMismatchException on invalid input |
nextDouble() | double | 99.99 | Accepts both 99.99 and 99,99 (locale-dependent) |
nextFloat() | float | 3.14 | Less precise than double; rarely needed |
nextLong() | long | 9876543210 | For large whole numbers |
nextShort() | short | 100 | Memory-efficient small integers |
nextByte() | byte | 5 | Tiny integers (-128 to 127) |
nextBoolean() | boolean | true or false | Case-insensitive: True, FALSE also work |
Reading Strings
1Scanner input = new Scanner(System.in); 2 3System.out.print("Enter your full name: "); 4String name = input.nextLine(); // Reads: "Rahul Sharma" 5 6System.out.print("Enter a keyword: "); 7String keyword = input.next(); // Reads only: "Java" (stops at space)
Reading Integers
1System.out.print("Enter your age: "); 2int age = input.nextInt(); 3System.out.println("You are " + age + " years old.");
Reading Floating-Point Numbers
1System.out.print("Enter your salary: "); 2double salary = input.nextDouble(); 3System.out.println("Salary: ₹" + salary);
Reading Characters
Scanner has no nextChar() method. This is a common interview question. The workaround:
1System.out.print("Enter your grade (A/B/C): "); 2char grade = input.next().charAt(0); 3System.out.println("Grade: " + grade);
How it works: next() reads a String (e.g., "A"), then charAt(0) extracts the first character.
Complete Example: User Profile
1import java.util.Scanner; 2 3public class UserProfile { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 7 System.out.print("Name: "); 8 String name = input.nextLine(); 9 10 System.out.print("Age: "); 11 int age = input.nextInt(); 12 13 System.out.print("Salary: "); 14 double salary = input.nextDouble(); 15 16 System.out.print("Is Employed (true/false): "); 17 boolean isEmployed = input.nextBoolean(); 18 19 System.out.println("\\n--- Profile ---"); 20 System.out.println("Name: " + name); 21 System.out.println("Age: " + age); 22 System.out.println("Salary: ₹" + salary); 23 System.out.println("Employed: " + isEmployed); 24 25 input.close(); 26 } 27}
The BufferedReader Class
BufferedReader is the performance champion for reading input. It reads data in chunks (buffers), making it significantly faster than Scanner for large volumes of text.
When to Use BufferedReader
- Competitive programming (speed matters)
- Reading large files line by line
- Processing massive text inputs
- When you only need
Stringinput (manual parsing)
Syntax
1import java.io.BufferedReader; 2import java.io.InputStreamReader; 3import java.io.IOException; 4 5BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
Example
1import java.io.*; 2 3public class BufferedReaderDemo { 4 public static void main(String[] args) throws IOException { 5 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 6 7 System.out.print("Enter your name: "); 8 String name = reader.readLine(); 9 10 System.out.print("Enter your age: "); 11 int age = Integer.parseInt(reader.readLine()); // Manual conversion! 12 13 System.out.println("Hello " + name + ", you are " + age + " years old."); 14 } 15}
Reading Different Types with BufferedReader
Since BufferedReader only reads String, you must manually convert:
1String line = reader.readLine(); 2 3int num = Integer.parseInt(line); // String → int 4double price = Double.parseDouble(line); // String → double 5float rate = Float.parseFloat(line); // String → float 6long population = Long.parseLong(line); // String → long 7boolean flag = Boolean.parseBoolean(line); // String → boolean
⚠️ The IOException Requirement
BufferedReader throws IOException on read errors. You must either:
- Add
throws IOExceptionto themainmethod - Wrap in a
try-catchblock
1// Option 1: throws 2try { 3 String data = reader.readLine(); 4} catch (IOException e) { 5 System.out.println("Error reading input: " + e.getMessage()); 6}
The Console Class
The Console class is Java's secure input specialist. It is the only built-in way to read passwords without displaying them on the screen.
When to Use Console
- Terminal-based password prompts
- Secure authentication scripts
- Command-line tools requiring hidden input
Syntax
1import java.io.Console; 2 3Console console = System.console();
Example: Secure Login
1import java.io.Console; 2 3public class SecureLogin { 4 public static void main(String[] args) { 5 Console console = System.console(); 6 7 if (console == null) { 8 System.out.println("Console not available. Run from terminal."); 9 return; 10 } 11 12 String username = console.readLine("Username: "); 13 char[] password = console.readPassword("Password: "); 14 15 System.out.println("Welcome, " + username + "!"); 16 // In real apps, compare password hash, not plain text 17 } 18}
⚠️ Important: Console Returns null in IDEs
System.console() returns null when running inside most IDEs (IntelliJ, Eclipse, VS Code) because IDEs redirect standard I/O streams. It works correctly only when run from a terminal or command prompt:
1javac SecureLogin.java 2java SecureLogin
Output Methods
Java provides three ways to display output via System.out:
1. System.out.print() — No Newline
Prints text and keeps the cursor on the same line.
1System.out.print("Loading"); 2System.out.print("..."); 3System.out.print("Done!"); 4// Output: Loading...Done!
2. System.out.println() — With Newline
Prints text and moves the cursor to the next line.
1System.out.println("Java"); 2System.out.println("Programming"); 3// Output: 4// Java 5// Programming
3. System.out.printf() — Formatted Output
The most powerful output method. It uses format specifiers to control exactly how data appears.
1String name = "Rahul"; 2int age = 20; 3double marks = 87.456; 4 5System.out.printf("Name: %s, Age: %d, Marks: %.2f%n", name, age, marks); 6// Output: Name: Rahul, Age: 20, Marks: 87.46
Output Formatting with printf
printf is borrowed from the C language and is incredibly powerful for creating professional-looking output.
Format Specifiers
| Specifier | Type | Example | Output |
|---|---|---|---|
%s | String | printf("%s", "Java") | Java |
%d | Integer | printf("%d", 42) | 42 |
%f | Float/Double | printf("%f", 3.14) | 3.140000 |
%.2f | Float (2 decimals) | printf("%.2f", 3.14159) | 3.14 |
%c | Character | printf("%c", \'A\') | A |
%b | Boolean | printf("%b", true) | true |
%n | Newline | printf("Line 1%nLine 2") | Platform-independent \\n |
%% | Literal % | printf("50%%") | 50% |
Width and Alignment
1// Right-align in 15 characters 2System.out.printf("%15s%n", "Laptop"); 3// Output: " Laptop" 4 5// Left-align in 15 characters 6System.out.printf("%-15s%n", "Laptop"); 7// Output: "Laptop " 8 9// Number with width 10 and 2 decimals 10System.out.printf("%10.2f%n", 59999.95); 11// Output: " 59999.95"
Real-World Example: Formatted Bill
1public class FormattedBill { 2 public static void main(String[] args) { 3 String product = "Wireless Mouse"; 4 double price = 1299.50; 5 int qty = 3; 6 double total = price * qty; 7 8 System.out.println("========== INVOICE =========="); 9 System.out.printf("%-20s %10s %10s %12s%n", "Product", "Price", "Qty", "Total"); 10 System.out.println("------------------------------------------------"); 11 System.out.printf("%-20s %10.2f %10d %12.2f%n", product, price, qty, total); 12 System.out.println("================================================"); 13 } 14}
Output:
1========== INVOICE ========== 2Product Price Qty Total 3------------------------------------------------ 4Wireless Mouse 1299.50 3 3898.50 5================================================
Input Method Comparison
| Feature | Scanner | BufferedReader | Console |
|---|---|---|---|
| Ease of Use | ⭐⭐⭐ Excellent | ⭐⭐ Moderate | ⭐⭐⭐ Excellent |
| Type Parsing | ✅ Built-in | ❌ Manual | ❌ Manual |
| Speed | Moderate | 🚀 Fast | Moderate |
| Exception Handling | Not required | Required (IOException) | Not required |
| Password Security | ❌ Visible | ❌ Visible | ✅ Hidden |
| IDE Compatibility | ✅ Works everywhere | ✅ Works everywhere | ❌ Returns null in IDEs |
| Best For | Beginners, general apps | Competitive programming, large files | Terminal scripts, secure input |
Decision Tree
Need to read password securely?
├── YES → Use Console (run from terminal)
└── NO → Reading massive text / competitive coding?
├── YES → Use BufferedReader
└── NO → Use Scanner (default choice)
Real-World Use Cases
Use Case 1: E-Commerce Checkout Flow
1import java.util.Scanner; 2 3public class Checkout { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 7 System.out.print("Product Name: "); 8 String product = input.nextLine(); 9 10 System.out.print("Unit Price: "); 11 double price = input.nextDouble(); 12 13 System.out.print("Quantity: "); 14 int qty = input.nextInt(); 15 16 double subtotal = price * qty; 17 double tax = subtotal * 0.18; // 18% GST 18 double total = subtotal + tax; 19 20 System.out.println("\\n========== RECEIPT =========="); 21 System.out.printf("%-20s: %s%n", "Product", product); 22 System.out.printf("%-20s: %.2f x %d%n", "Price x Qty", price, qty); 23 System.out.printf("%-20s: ₹%.2f%n", "Subtotal", subtotal); 24 System.out.printf("%-20s: ₹%.2f%n", "Tax (18%)", tax); 25 System.out.printf("%-20s: ₹%.2f%n", "TOTAL", total); 26 System.out.println("============================="); 27 28 input.close(); 29 } 30}
Use Case 2: Student Grade Management
1import java.util.Scanner; 2 3public class GradeManager { 4 public static void main(String[] args) { 5 Scanner input = new Scanner(System.in); 6 7 System.out.print("Student Name: "); 8 String name = input.nextLine(); 9 10 System.out.print("Marks in Math: "); 11 int math = input.nextInt(); 12 13 System.out.print("Marks in Science: "); 14 int science = input.nextInt(); 15 16 System.out.print("Marks in English: "); 17 int english = input.nextInt(); 18 19 int total = math + science + english; 20 double average = total / 3.0; 21 22 String grade = (average >= 90) ? "A+" : 23 (average >= 80) ? "A" : 24 (average >= 70) ? "B" : 25 (average >= 60) ? "C" : 26 (average >= 40) ? "D" : "F"; 27 28 System.out.println("\\n--- RESULT CARD ---"); 29 System.out.printf("Student: %s%n", name); 30 System.out.printf("Total: %d/300%n", total); 31 System.out.printf("Average: %.2f%%%n", average); 32 System.out.printf("Grade: %s%n", grade); 33 34 input.close(); 35 } 36}
Use Case 3: Configuration File Reader (BufferedReader)
1import java.io.*; 2 3public class ConfigReader { 4 public static void main(String[] args) throws IOException { 5 BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); 6 7 System.out.println("Enter configuration (key=value), type \"done\" to finish:"); 8 9 String line; 10 while (!(line = reader.readLine()).equalsIgnoreCase("done")) { 11 String[] parts = line.split("="); 12 System.out.printf("Key: %-15s | Value: %s%n", parts[0], parts[1]); 13 } 14 15 System.out.println("Configuration loaded successfully."); 16 } 17}
Common Mistakes
Mistake 1: The nextInt() + nextLine() Trap
This is the #1 bug every beginner hits. After nextInt(), the newline character remains in the buffer, causing nextLine() to read an empty string.
1// WRONG — nextLine() reads empty string! 2Scanner input = new Scanner(System.in); 3 4System.out.print("Age: "); 5int age = input.nextInt(); // User types "20" and presses Enter 6 7System.out.print("Name: "); 8String name = input.nextLine(); // Reads the leftover "\\n", name = ""
Fix 1: Add an extra nextLine() to consume the newline:
1int age = input.nextInt(); 2input.nextLine(); // Consume the leftover newline! 3String name = input.nextLine();
Fix 2 (Best): Use nextLine() for everything and parse manually:
1System.out.print("Age: "); 2int age = Integer.parseInt(input.nextLine()); 3 4System.out.print("Name: "); 5String name = input.nextLine(); // Works perfectly!
Mistake 2: Forgetting to Close the Scanner
1// BAD — Resource leak 2Scanner input = new Scanner(System.in); 3// ... read input ... 4// Forgot input.close()!
Fix: Always close resources. Better yet, use try-with-resources:
1try (Scanner input = new Scanner(System.in)) { 2 // ... read input ... 3} // Automatically closed here!
Mistake 3: Not Handling Invalid Input
1// CRASHES if user types "abc" instead of a number! 2int age = input.nextInt();
Fix: Validate with hasNextInt():
1System.out.print("Enter age: "); 2while (!input.hasNextInt()) { 3 System.out.println("Invalid input. Please enter a number."); 4 input.next(); // Discard invalid token 5} 6int age = input.nextInt();
Mistake 4: Using == for String Comparison After Input
1// WRONG — compares memory addresses, not content 2if (input.next() == "yes") { // Always false! 3} 4 5// CORRECT — compares string content 6if (input.next().equals("yes")) { 7} 8 9// EVEN BETTER — case-insensitive 10if (input.next().equalsIgnoreCase("yes")) { 11}
Mistake 5: Assuming Console Works in IDEs
1Console console = System.console(); 2if (console == null) { 3 System.out.println("Please run this program from a terminal."); 4 return; 5}
Always check for null before using Console.
Best Practices
-
Use try-with-resources for Scanner
1try (Scanner input = new Scanner(System.in)) { 2 // Your input logic 3} -
Validate all user input — Never trust what the user types. Check types, ranges, and formats.
-
Use
nextLine()+ manual parsing to avoid the newline trap:1int age = Integer.parseInt(input.nextLine()); -
Prefer
printf()for tabular output — It creates professional, aligned displays. -
Choose the right tool for the job:
- General apps →
Scanner - Speed-critical / large data →
BufferedReader - Secure terminal input →
Console
- General apps →
-
Always provide clear prompts — Tell the user exactly what to type:
1// Good 2System.out.print("Enter your age (1-120): "); 3 4// Bad 5System.out.print("Enter: "); -
Handle
InputMismatchException— Wrap parsing in try-catch for production apps.
Architecture & Performance Considerations
Scanner Under the Hood
Scanner uses regular expressions to parse tokens. This makes it flexible but slightly slower than BufferedReader. For most applications, the difference is negligible. For processing millions of lines, BufferedReader wins.
BufferedReader Performance
BufferedReader reads 8KB (or more) chunks at a time, reducing system calls. In competitive programming, this can be the difference between a "Time Limit Exceeded" (TLE) and an "Accepted" (AC) verdict.
Console and Security
Console.readPassword() returns a char[] instead of a String. This is intentional:
Stringis immutable and stays in memory until garbage collectedchar[]can be manually overwritten after use, reducing the password's memory footprint
1char[] password = console.readPassword("Password: "); 2// ... authenticate ... 3java.util.Arrays.fill(password, \' \'); // Clear from memory
Input Streams in Web Applications
In Spring Boot or Jakarta EE, user input comes via HTTP requests (JSON, form data), not System.in. However, the principles of validation, parsing, and formatted output remain identical. Mastering console I/O builds the foundation for handling API request bodies.
Practice Programs
Exercise 1: Personal Information Card
Write a program that asks for name, age, city, and phone number, then displays a formatted card.
1import java.util.Scanner; 2 3public class PersonalCard { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Name: "); 7 String name = input.nextLine(); 8 9 System.out.print("Age: "); 10 int age = Integer.parseInt(input.nextLine()); 11 12 System.out.print("City: "); 13 String city = input.nextLine(); 14 15 System.out.print("Phone: "); 16 String phone = input.nextLine(); 17 18 System.out.println("\\n+----------------------------+"); 19 System.out.println("| PERSONAL DETAILS |"); 20 System.out.println("+----------------------------+"); 21 System.out.printf("| %-10s: %-14s|%n", "Name", name); 22 System.out.printf("| %-10s: %-14d|%n", "Age", age); 23 System.out.printf("| %-10s: %-14s|%n", "City", city); 24 System.out.printf("| %-10s: %-14s|%n", "Phone", phone); 25 System.out.println("+----------------------------+"); 26 } 27 } 28}
Exercise 2: Simple Interest Calculator
1import java.util.Scanner; 2 3public class SimpleInterest { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Principal Amount: "); 7 double principal = Double.parseDouble(input.nextLine()); 8 9 System.out.print("Rate of Interest (%): "); 10 double rate = Double.parseDouble(input.nextLine()); 11 12 System.out.print("Time (years): "); 13 double time = Double.parseDouble(input.nextLine()); 14 15 double interest = (principal * rate * time) / 100; 16 double total = principal + interest; 17 18 System.out.println("\\n--- SIMPLE INTEREST ---"); 19 System.out.printf("Principal: ₹%.2f%n", principal); 20 System.out.printf("Rate: %.2f%%%n", rate); 21 System.out.printf("Time: %.1f years%n", time); 22 System.out.printf("Interest: ₹%.2f%n", interest); 23 System.out.printf("Total: ₹%.2f%n", total); 24 } 25 } 26}
Exercise 3: Grade Calculator
1import java.util.Scanner; 2 3public class GradeCalculator { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Subject 1 Marks: "); 7 double s1 = Double.parseDouble(input.nextLine()); 8 9 System.out.print("Subject 2 Marks: "); 10 double s2 = Double.parseDouble(input.nextLine()); 11 12 System.out.print("Subject 3 Marks: "); 13 double s3 = Double.parseDouble(input.nextLine()); 14 15 double total = s1 + s2 + s3; 16 double avg = total / 3.0; 17 18 System.out.printf("\\nTotal: %.2f%n", total); 19 System.out.printf("Average: %.2f%%%n", avg); 20 } 21 } 22}
Exercise 4: Employee Salary Slip
1import java.util.Scanner; 2 3public class SalarySlip { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Employee Name: "); 7 String name = input.nextLine(); 8 9 System.out.print("Basic Salary: "); 10 double basic = Double.parseDouble(input.nextLine()); 11 12 double hra = basic * 0.20; // 20% HRA 13 double da = basic * 0.10; // 10% DA 14 double gross = basic + hra + da; 15 16 System.out.println("\\n========== SALARY SLIP =========="); 17 System.out.printf("%-20s: %s%n", "Employee", name); 18 System.out.printf("%-20s: ₹%10.2f%n", "Basic Salary", basic); 19 System.out.printf("%-20s: ₹%10.2f%n", "HRA (20%)", hra); 20 System.out.printf("%-20s: ₹%10.2f%n", "DA (10%)", da); 21 System.out.println("-----------------------------------"); 22 System.out.printf("%-20s: ₹%10.2f%n", "Gross Salary", gross); 23 System.out.println("==================================="); 24 } 25 } 26}
Exercise 5: Multi-Product Shopping Bill
1import java.util.Scanner; 2 3public class ShoppingBill { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 double grandTotal = 0; 7 8 System.out.println("Enter details for 3 products:"); 9 System.out.println(); 10 11 for (int i = 1; i <= 3; i++) { 12 System.out.print("Product " + i + " Name: "); 13 String name = input.nextLine(); 14 15 System.out.print("Price: "); 16 double price = Double.parseDouble(input.nextLine()); 17 18 System.out.print("Quantity: "); 19 int qty = Integer.parseInt(input.nextLine()); 20 21 double total = price * qty; 22 grandTotal += total; 23 24 System.out.printf("Line Total: ₹%.2f%n%n", total); 25 } 26 27 System.out.println("========== FINAL BILL =========="); 28 System.out.printf("Grand Total: ₹%.2f%n", grandTotal); 29 } 30 } 31}
Mini Project: ATM Simulator
Build a console-based ATM that demonstrates input validation, formatted output, and decision-making.
1import java.util.Scanner; 2 3public class ATMSimulator { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 double balance = 5000.00; 7 int pin = 1234; 8 boolean running = true; 9 10 System.out.println("========== WELCOME TO TECH3 BANK =========="); 11 System.out.print("Enter your 4-digit PIN: "); 12 int enteredPin = input.nextInt(); 13 14 if (enteredPin != pin) { 15 System.out.println("❌ Invalid PIN. Access denied."); 16 return; 17 } 18 19 while (running) { 20 System.out.println("\\n--- MAIN MENU ---"); 21 System.out.println("1. Check Balance"); 22 System.out.println("2. Deposit"); 23 System.out.println("3. Withdraw"); 24 System.out.println("4. Exit"); 25 System.out.print("Select option (1-4): "); 26 27 int choice = input.nextInt(); 28 29 switch (choice) { 30 case 1: 31 System.out.printf("\\n💰 Current Balance: ₹%.2f%n", balance); 32 break; 33 34 case 2: 35 System.out.print("Enter deposit amount: "); 36 double deposit = input.nextDouble(); 37 if (deposit > 0) { 38 balance += deposit; 39 System.out.printf("✅ ₹%.2f deposited successfully.%n", deposit); 40 System.out.printf("New Balance: ₹%.2f%n", balance); 41 } else { 42 System.out.println("❌ Invalid amount."); 43 } 44 break; 45 46 case 3: 47 System.out.print("Enter withdrawal amount: "); 48 double withdraw = input.nextDouble(); 49 if (withdraw > 0 && withdraw <= balance) { 50 balance -= withdraw; 51 System.out.printf("✅ ₹%.2f withdrawn successfully.%n", withdraw); 52 System.out.printf("New Balance: ₹%.2f%n", balance); 53 } else if (withdraw > balance) { 54 System.out.println("❌ Insufficient balance."); 55 } else { 56 System.out.println("❌ Invalid amount."); 57 } 58 break; 59 60 case 4: 61 System.out.println("\\n👋 Thank you for banking with us!"); 62 running = false; 63 break; 64 65 default: 66 System.out.println("❌ Invalid option. Please try again."); 67 } 68 } 69 } 70 } 71}
What This Project Covers:
Scannerfor all input types (int,double)- Input validation (PIN check, amount validation)
switchstatements for menu navigation- Formatted output with
printf() - Looping for continuous interaction
- Real-world logic (insufficient balance checks)
Summary & Cheat Sheet
Quick Reference
| Task | Method | Example |
|---|---|---|
| Read String (one word) | next() | input.next() |
| Read String (full line) | nextLine() | input.nextLine() |
| Read Integer | nextInt() | input.nextInt() |
| Read Double | nextDouble() | input.nextDouble() |
| Read Character | next().charAt(0) | input.next().charAt(0) |
| Print without newline | print() | System.out.print("Hi") |
| Print with newline | println() | System.out.println("Hi") |
| Print formatted | printf() | System.out.printf("%.2f", val) |
| Format String | %s | printf("%s", name) |
| Format Integer | %d | printf("%d", age) |
| Format Double (2 decimals) | %.2f | printf("%.2f", price) |
| Newline in printf | %n | printf("Line 1%nLine 2") |
Key Takeaways
- Scanner is your default friend — Use it for 90% of console applications.
- The
nextInt()+nextLine()trap is real — UsenextLine()+Integer.parseInt()to avoid it. - Always close resources — Use try-with-resources for clean, safe code.
printf()is professional — Master format specifiers for polished output.- Choose tools wisely — Scanner for ease, BufferedReader for speed, Console for security.
- Never trust user input — Validate types, ranges, and formats before processing.
What's Next?
Now that you can accept and display data, you're ready to make your programs intelligent:
- Control Flow Statements (
if,else,switch) - Loops (
for,while,do-while) - Methods & Functions (reusable logic blocks)
- Arrays & Collections (storing multiple values)
Input and output are the bridge between your code and the real world. Master them, and every program you build becomes interactive and useful.