Java Input/Output (I/O) and Scanner

Master reading user input and displaying output in Java using Scanner and other methods

What is Input/Output in Java?

Input/Output (I/O) is how your Java program communicates with the user. Input is when your program receives data from the user, and Output is when your program displays results to the user. Think of it like a conversation: your program asks a question (output), and the user types an answer (input).

  • Output: Displaying information to the user using System.out.println()
  • Input: Receiving data from the user using Scanner class
  • Streams: Channels through which data flows between your program and the user

Real-Life Example: When you use an ATM, the machine displays balance (output) and waits for you to enter your PIN (input). Java programs work similarly!

Output: Displaying Information

The easiest way to display output in Java is using the System.out object. There are three main methods:

1. System.out.println()

Prints text and automatically adds a new line after it. Most commonly used method.

Example: Good for printing complete messages or lines of output.

2. System.out.print()

Prints text WITHOUT adding a new line. Useful when you want text on the same line.

Example: Good for printing multiple items on one line.

3. System.out.printf()

Formats output with specific formatting options. Powerful for creating formatted output.

Example: Good for aligning numbers, decimals, or currency values.

Output Examples

Let's see the difference between println(), print(), and printf():

Example: Different Output Methods

public class OutputExample {
    public static void main(String[] args) {
        // println() - prints with new line
        System.out.println("This is line 1");
        System.out.println("This is line 2");
        
        System.out.println(""); // blank line
        
        // print() - prints without new line
        System.out.print("Hello ");
        System.out.print("World!");
        System.out.println(); // move to next line
        
        System.out.println(""); // blank line
        
        // printf() - formatted output
        System.out.printf("My name is %s and I am %d years old%n", "John", 20);
        System.out.printf("Price: $%.2f%n", 19.5);
    }
}
Output:
This is line 1
This is line 2

Hello World!

My name is John and I am 20 years old
Price: $19.50

Explanation:

  • println() prints each statement on a separate line
  • print() keeps text on the same line until println() is used
  • %s is a placeholder for String, %d for integer, %.2f for decimal with 2 places, %n for new line

Input: Using the Scanner Class

The Scanner class is used to read input from the user. It's like opening a door to receive data. Before using it, you must import it from Java's utilities package.

Important: Always add this line at the top of your code to use Scanner: import java.util.Scanner;

Basic Steps to use Scanner:

  • Import the Scanner class
  • Create a Scanner object linked to System.in (keyboard input)
  • Use Scanner methods to read different types of data
  • Close the Scanner when done (optional but good practice)

Common Scanner Methods

1. nextInt()

Reads an integer (whole number) from the user.

Usage: int age = scanner.nextInt();

2. nextDouble()

Reads a decimal number from the user.

Usage: double price = scanner.nextDouble();

3. nextLine()

Reads an entire line of text (including spaces) from the user.

Usage: String name = scanner.nextLine();

4. next()

Reads a single word (text until first space) from the user.

Usage: String word = scanner.next();

5. nextBoolean()

Reads true or false from the user.

Usage: boolean isActive = scanner.nextBoolean();

First Scanner Program: Getting User's Name

This simple program asks the user for their name and displays a greeting:

Example: Reading a String with Scanner

import java.util.Scanner;

public class GreetingProgram {
    public static void main(String[] args) {
        // Create a Scanner object
        Scanner scanner = new Scanner(System.in);
        
        // Ask the user for their name
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        
        // Display greeting
        System.out.println("Hello, " + name + "! Welcome to Java!");
        
        // Close the scanner
        scanner.close();
    }
}
Output (with user input):
Enter your name: Alice
Hello, Alice! Welcome to Java!

Explanation:

  • new Scanner(System.in) creates a Scanner object that reads from keyboard
  • nextLine() reads the entire line of text that the user types
  • scanner.close() closes the Scanner and frees up resources

Calculator Program: Reading Numbers

Let's create a program that takes two numbers from the user and displays their sum:

Example: Reading Integers and Processing Input

import java.util.Scanner;

public class SimpleCalculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Get first number
        System.out.print("Enter first number: ");
        int num1 = scanner.nextInt();
        
        // Get second number
        System.out.print("Enter second number: ");
        int num2 = scanner.nextInt();
        
        // Calculate sum
        int sum = num1 + num2;
        
        // Display result
        System.out.println("Sum: " + sum);
        System.out.printf("Result: %d + %d = %d%n", num1, num2, sum);
        
        scanner.close();
    }
}
Output (with user input):
Enter first number: 10
Enter second number: 20
Sum: 30
Result: 10 + 20 = 30

Explanation:

  • nextInt() reads an integer value from the user
  • We use System.out.print() (without 'ln') to keep the input prompt on the same line
  • The program performs calculation and displays formatted output

Complete Input Program: Student Information

This program reads multiple types of data and displays a summary:

Example: Reading Multiple Data Types

import java.util.Scanner;

public class StudentInfo {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read student name
        System.out.print("Enter student name: ");
        String name = scanner.nextLine();
        
        // Read student age
        System.out.print("Enter age: ");
        int age = scanner.nextInt();
        
        // Read GPA
        System.out.print("Enter GPA: ");
        double gpa = scanner.nextDouble();
        
        // Display information
        System.out.println("\n--- Student Profile ---");
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.printf("GPA: %.2f%n", gpa);
        
        scanner.close();
    }
}
Output (with user input):
Enter student name: Emma
Enter age: 20
Enter GPA: 3.85

--- Student Profile ---
Name: Emma
Age: 20
GPA: 3.85

Explanation:

  • We use nextLine() for strings, nextInt() for integers, and nextDouble() for decimals
  • \n in println() creates a blank line for better formatting
  • printf() with %.2f displays the GPA with exactly 2 decimal places

Other Input Methods: BufferedReader

Besides Scanner, Java also provides BufferedReader as another way to read input. It's often used for reading lines of text efficiently:

Example: Using BufferedReader

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;

public class BufferedReaderExample {
    public static void main(String[] args) throws IOException {
        // Create BufferedReader object
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(System.in)
        );
        
        System.out.print("Enter your name: ");
        String name = reader.readLine();
        
        System.out.println("Hello, " + name);
        
        reader.close();
    }
}
Output (with user input):
Enter your name: Bob
Hello, Bob

Scanner vs BufferedReader:

  • Scanner: Easier to use, better for different data types, recommended for beginners
  • BufferedReader: Faster for large amounts of text, more complex to set up, requires error handling

Common I/O Mistakes to Avoid

❌ Mistake 1: Forgetting to import Scanner

You must add import java.util.Scanner; at the top of your program, or Scanner won't be recognized.

❌ Mistake 2: Using nextInt() then nextLine()

After nextInt(), there's a newline character left in the buffer. Use an extra nextLine() to clear it before reading a String.

❌ Mistake 3: Not Closing Scanner

While not required, it's good practice to close Scanner with scanner.close(); to free up system resources.

❌ Mistake 4: Wrong Scanner Method

Using next() when you need full text with spaces? Use nextLine() instead. next() stops at the first space.

Solution: Mixing nextInt() and nextLine()

Here's the correct way to mix integer and string input:

Example: Correct Handling of Different Input Types

import java.util.Scanner;

public class MixedInputCorrect {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read age (integer)
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        
        // IMPORTANT: Clear the buffer
        scanner.nextLine();
        
        // Read name (string with spaces)
        System.out.print("Enter your full name: ");
        String name = scanner.nextLine();
        
        System.out.println("Age: " + age);
        System.out.println("Name: " + name);
        
        scanner.close();
    }
}
Output (with user input):
Enter your age: 25
Enter your full name: John Smith
Age: 25
Name: John Smith

Why This Works:

  • After reading 25 with nextInt(), a newline character stays in the buffer
  • The extra scanner.nextLine() clears this newline
  • Now when we use nextLine() for the name, it correctly reads the full line

Quick Summary

Output Methods:

System.out.println() - Print with new line
System.out.print() - Print without new line
System.out.printf() - Formatted print

Scanner Methods:

nextInt() - Read integer
nextDouble() - Read decimal
nextLine() - Read entire line
next() - Read single word
nextBoolean() - Read true/false

Remember: Always import Scanner and close it when done!