Input & Output in Java (Scanner & System.out)

🟢 Beginner Level | Core Fundamentals

📖 Definition & Purpose

Java handles console output using System.out.println() and System.out.printf(), and parses user console input using the java.util.Scanner class or BufferedReader.

🌐 Multilingual Explanations

English

System.out.println() prints output followed by a new line. Scanner parses primitives and strings from System.in.

Hindi

User se input lene ke liye Scanner sc = new Scanner(System.in) use hota hai, aur output ke liye System.out.println().

Marathi

Console var input ghenyasathi Scanner class vapra aani display sathi System.out.println().

Hinglish

Scanner = User input reader (`sc.nextInt()`, `sc.nextLine()`). System.out.printf = Formatted output with `%d`, `%s`, `%.2f` placeholders.

💡 Production Code Example

import java.util.Scanner;

public class UserInputDemo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        System.out.print("Enter your age: ");
        int age = scanner.nextInt();

        System.out.printf("User: %s | Age: %d years old%n", name, age);
        scanner.close();
    }
}

🖥️ Expected Output

Enter your name: Alex
Enter your age: 24
User: Alex | Age: 24 years old

⚠️ Common Pitfalls

Scanner Newline Bug: Calling scanner.nextLine() immediately after scanner.nextInt() reads the leftover newline character instead of waiting for user text input! Fix by calling an extra scanner.nextLine() to clear the buffer.

🎯 Tiered Practice Exercises

  1. Beginner: Write a Java program asking user for 2 integers and printing their sum.
  2. Intermediate: Ask user for item price and quantity, then display total formatted to 2 decimal places using System.out.printf("Total: $%.2f").
  3. Advanced: Build a student registration form asking for Name, Roll Number, and GPA with input validation.

🧭 Navigation

← 03. Variables | Course Overview | 05. Operators →