Lesson Completion
Back to course

Input and Output: Reading Input and Displaying Output

Beginner
10 minutes4.8Java

1. The Hook (The "Byte-Sized" Intro)

  • In a Nutshell: Output: print() (no newline), println() (with newline), printf() (formatted with %d, %s, %f).
  • Input: Scanner class (easy, common), nextInt(), nextLine(), nextDouble().
  • Format specifiers: %d (int), %s (String), %f (float/double), %.2f (2 decimals). BufferedReader (faster for large input).
  • Common issue: nextInt() doesn't consume newline—use nextLine() after! Golden rule: Always close Scanner/BufferedReader when done (use try-with-resources)!

Think of conversation. Output = speaking (print, println, printf). Input = listening (Scanner). printf = formal speech (structured format). nextLine() issue = person pauses mid-sentence (need to wait for full response)!


2. Conceptual Clarity (The "Simple" Tier)

💡 The Analogy

  • print(): Write on same line (no paragraph break)
  • println(): Write and press Enter (new line)
  • printf(): Fill-in-the-blank form (%s = name, %d = age)
  • Scanner: Microphone (capture user input)

3. Technical Mastery (The "Deep Dive")

java
// =========================================== // 1. OUTPUT METHODS // =========================================== // print() - No newline at end System.out.print("Hello"); System.out.print(" World"); // Output: Hello World (same line) // println() - Adds newline at end System.out.println("Hello"); System.out.println("World"); // Output: // Hello // World // printf() - Formatted output String name = "Alice"; int age = 25; double salary = 75000.50; System.out.printf("Name: %s, Age: %d, Salary: $%.2f%n", name, age, salary); // Output: Name: Alice, Age: 25, Salary: $75000.50 // =========================================== // 2. FORMAT SPECIFIERS (printf) // =========================================== // %d - Integer (decimal) int count = 42; System.out.printf("Count: %d%n", count); // Count: 42 // %s - String String message = "Hello"; System.out.printf("Message: %s%n", message); // Message: Hello // %f - Floating-point (default 6 decimals) double pi = 3.14159; System.out.printf("Pi: %f%n", pi); // Pi: 3.141590 // %.2f - Floating-point with 2 decimals double price = 19.99; System.out.printf("Price: $%.2f%n", price); // Price: $19.99 // %c - Character char grade = 'A'; System.out.printf("Grade: %c%n", grade); // Grade: A // %b - Boolean boolean isActive = true; System.out.printf("Active: %b%n", isActive); // Active: true // %n - Platform-independent newline (recommended over \n) // Multiple placeholders System.out.printf("Name: %s, Age: %d, GPA: %.2f%n", "Bob", 22, 3.75); // Width and alignment System.out.printf("%10s%n", "Right"); // " Right" (right-aligned, width 10) System.out.printf("%-10s%n", "Left"); // "Left " (left-aligned, width 10) System.out.printf("%05d%n", 42); // "00042" (zero-padded, width 5) // =========================================== // 3. SCANNER CLASS (Input) // =========================================== import java.util.Scanner; // Create Scanner (reads from System.in) Scanner scanner = new Scanner(System.in); // Read different types System.out.print("Enter your name: "); String name = scanner.nextLine(); // Read entire line System.out.print("Enter your age: "); int age = scanner.nextInt(); // Read integer System.out.print("Enter your GPA: "); double gpa = scanner.nextDouble(); // Read double System.out.print("Is student? (true/false): "); boolean isStudent = scanner.nextBoolean(); scanner.close(); // ✅ Always close! // =========================================== // 4. SCANNER METHODS // =========================================== Scanner sc = new Scanner(System.in); // Read methods String line = sc.nextLine(); // Read entire line (until Enter) String word = sc.next(); // Read single word (until space) int num = sc.nextInt(); // Read integer double decimal = sc.nextDouble(); // Read double boolean flag = sc.nextBoolean(); // Read boolean byte b = sc.nextByte(); short s = sc.nextShort(); long l = sc.nextLong(); float f = sc.nextFloat(); // Check if input available if (sc.hasNextInt()) { int value = sc.nextInt(); } else { System.out.println("Not an integer!"); } // =========================================== // 5. COMMON SCANNER PITFALL (nextInt + nextLine) // =========================================== // ❌ PROBLEM: nextInt() doesn't consume newline! Scanner input = new Scanner(System.in); System.out.print("Enter age: "); int age = input.nextInt(); // Reads 25, leaves '\n' in buffer! System.out.print("Enter name: "); String name = input.nextLine(); // ❌ Reads empty string (the '\n')! System.out.println("Age: " + age); // 25 System.out.println("Name: " + name); // "" (empty!) // ✅ FIX: Consume leftover newline Scanner fixed = new Scanner(System.in); System.out.print("Enter age: "); int fixedAge = fixed.nextInt(); fixed.nextLine(); // ✅ Consume the newline! System.out.print("Enter name: "); String fixedName = fixed.nextLine(); // ✅ Now works correctly! // =========================================== // 6. TRY-WITH-RESOURCES (Auto-close) // =========================================== // ✅ BEST PRACTICE: Auto-close Scanner try (Scanner scanner = new Scanner(System.in)) { System.out.print("Enter name: "); String name = scanner.nextLine(); System.out.print("Enter age: "); int age = scanner.nextInt(); System.out.printf("Hello, %s! You are %d years old.%n", name, age); } // ✅ Scanner automatically closed here! // =========================================== // 7. BUFFEREDREADER (Faster for Large Input) // =========================================== import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) { System.out.print("Enter name: "); String name = reader.readLine(); // Read line System.out.print("Enter age: "); String ageStr = reader.readLine(); int age = Integer.parseInt(ageStr); // Convert to int System.out.printf("Name: %s, Age: %d%n", name, age); } catch (IOException e) { e.printStackTrace(); } // BufferedReader vs Scanner: // - BufferedReader: Faster, more efficient for large input // - Scanner: Easier to use, has nextInt(), nextDouble(), etc. // =========================================== // 8. PRACTICAL EXAMPLES // =========================================== // Example 1: Simple Calculator try (Scanner sc = new Scanner(System.in)) { System.out.print("Enter first number: "); double num1 = sc.nextDouble(); System.out.print("Enter second number: "); double num2 = sc.nextDouble(); double sum = num1 + num2; System.out.printf("Sum: %.2f%n", sum); } // Example 2: Student Registration try (Scanner sc = new Scanner(System.in)) { System.out.print("Enter student name: "); String name = sc.nextLine(); System.out.print("Enter age: "); int age = sc.nextInt(); sc.nextLine(); // Consume newline System.out.print("Enter email: "); String email = sc.nextLine(); System.out.println("\n--- Student Info ---"); System.out.printf("Name: %s%n", name); System.out.printf("Age: %d%n", age); System.out.printf("Email: %s%n", email); } // Example 3: Formatted Invoice double item1 = 19.99; double item2 = 5.50; double item3 = 12.75; double total = item1 + item2 + item3; double tax = total * 0.08; double grandTotal = total + tax; System.out.println("========== INVOICE =========="); System.out.printf("Item 1: $%8.2f%n", item1); System.out.printf("Item 2: $%8.2f%n", item2); System.out.printf("Item 3: $%8.2f%n", item3); System.out.println("-----------------------------"); System.out.printf("Subtotal: $%8.2f%n", total); System.out.printf("Tax (8%%): $%8.2f%n", tax); System.out.println("============================="); System.out.printf("TOTAL: $%8.2f%n", grandTotal);

5. The Comparison & Decision Layer

MethodPurposeNewline?Example
print()Output without newlineNoSystem.out.print("Hi");
println()Output with newlineYesSystem.out.println("Hi");
printf()Formatted outputOptional (%n)System.out.printf("%s", "Hi");
Scanner.nextLine()Read entire lineYesscanner.nextLine();
Scanner.nextInt()Read integerNo ⚠️scanner.nextInt();

6. The "Interview Corner" (The Edge)

The "Killer" Interview Question: "What's the issue with using nextInt() followed by nextLine()?" Answer: nextInt() doesn't consume the newline character!

java
Scanner sc = new Scanner(System.in); System.out.print("Age: "); int age = sc.nextInt(); // Input: 25<Enter> // Reads "25", leaves "\n" in buffer System.out.print("Name: "); String name = sc.nextLine(); // ❌ Reads "\n" (empty!) // ✅ FIX: Consume the newline int age = sc.nextInt(); sc.nextLine(); // ✅ Consume "\n" String name = sc.nextLine(); // ✅ Now works!

Pro-Tips:

  1. Format specifier cheat sheet:
java
System.out.printf("%d%n", 42); // Integer: 42 System.out.printf("%5d%n", 42); // Width 5, right-aligned: " 42" System.out.printf("%-5d%n", 42); // Width 5, left-aligned: "42 " System.out.printf("%05d%n", 42); // Zero-padded: "00042" System.out.printf("%.2f%n", 3.14159); // 2 decimals: 3.14 System.out.printf("%8.2f%n", 3.14); // Width 8, 2 decimals: " 3.14" System.out.printf("%s%n", "Hello"); // String: Hello System.out.printf("%10s%n", "Hi"); // Right-aligned: " Hi" System.out.printf("%-10s%n", "Hi"); // Left-aligned: "Hi "
  1. Input validation:
java
Scanner sc = new Scanner(System.in); System.out.print("Enter age: "); while (!sc.hasNextInt()) { // Validate input System.out.print("Invalid! Enter a number: "); sc.next(); // Clear invalid input } int age = sc.nextInt(); // ✅ Guaranteed to be int

Topics Covered

Java FundamentalsJava Syntax

Tags

#java#basics#syntax#variables#data-types#beginner-friendly

Last Updated

2025-02-01