Java Tutorial » Chapter 9 — Input/Output

Chapter 9 — Java Input/Output

Learn how to interact with the user by displaying and reading data.

1. Introduction

What is Input/Output (I/O)?

Input/Output, or I/O, is how a program communicates with the outside world. For a simple console application, this means:

  • Output: Displaying information on the screen for the user to see.
  • Input: Reading data that the user types on the keyboard.

Java provides a rich set of tools for handling I/O, and we'll start with the most basic ones for console applications.

2. Output to Console

Displaying Information

The most common way to produce output in Java is by using the `System.out` object. It has three main methods for printing text.

System.out.println()

This method prints the text you provide to the console and then moves the cursor to a new line. "println" stands for "print line".

public class PrintlnExample {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
        System.out.println("This is on a new line.");
        System.out.println(123); // You can also print variables
    }
}

System.out.print()

This method prints the text but keeps the cursor on the same line. This is useful for prompting the user for input.

public class PrintExample {
    public static void main(String[] args) {
        System.out.print("Enter your name: ");
        System.out.print("Your name will appear here.");
    }
}

System.out.printf()

This method allows for formatted printing, similar to the `printf` function in C. You can use format specifiers to control how data is displayed.

  • %s for a String
  • %d for an integer
  • %f for a floating-point number
  • %n for a platform-independent new line character
public class PrintfExample {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 30;
        double height = 5.6;

        System.out.printf("Name: %s%n", name);
        System.out.printf("Age: %d years%n", age);
        System.out.printf("Height: %.2f feet%n", height); // .2f rounds to 2 decimal places
    }
}
3. Input from Console

Reading User Input

The easiest way to read input from the keyboard in Java is by using the `Scanner` class, which is part of Java's utility library.

Steps to Use the Scanner Class:

  1. Import the class: At the top of your file, add import java.util.Scanner;.
  2. Create a Scanner object: In your method, create a new Scanner object that reads from standard input (the keyboard): Scanner scanner = new Scanner(System.in);.
  3. Read the input: Use one of the scanner's methods (like nextInt(), nextLine()) to read the data.
  4. Close the scanner: When you are done, it's good practice to close the scanner to release system resources: scanner.close();.
4. Reading Different Types

Reading Strings, Integers, and More

The `Scanner` class provides different methods for reading different data types. Here is a complete example showing how to read several common types.

import java.util.Scanner; // 1. Import the Scanner class

public class InputExample {
    public static void main(String[] args) {
        // 2. Create a Scanner object
        Scanner scanner = new Scanner(System.in);

        // --- Reading a String ---
        System.out.print("Enter your full name: ");
        String fullName = scanner.nextLine(); // Reads the entire line of text

        // --- Reading an Integer ---
        System.out.print("Enter your age: ");
        int age = scanner.nextInt(); // Reads the next integer value

        // --- Reading a Double ---
        System.out.print("Enter your GPA: ");
        double gpa = scanner.nextDouble(); // Reads the next double value

        // --- Reading a Single Character ---
        System.out.print("Enter your grade (A, B, C, etc.): ");
        char grade = scanner.next().charAt(0); // Reads the next token, then gets the first char

        // --- Displaying all the information ---
        System.out.println("\n--- Your Information ---");
        System.out.println("Name: " + fullName);
        System.out.println("Age: " + age);
        System.out.println("GPA: " + gpa);
        System.out.println("Grade: " + grade);

        // 4. Close the scanner
        scanner.close();
    }
}

Note: scanner.next() reads only a single "token" (a word up to the next space). scanner.nextLine() reads the entire line, including spaces.

5. Common Input Issues

The NextLine Problem

A very common issue for beginners occurs when you mix methods like nextInt() or nextDouble() with nextLine().

The Problem: Methods like nextInt() read only the number, but they leave the "newline" character (created when you press Enter) in the input buffer. The very next nextLine() call then reads this leftover newline character and immediately finishes, skipping your actual input.

import java.util.Scanner;

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

        System.out.print("Enter your age: ");
        int age = scanner.nextInt(); // Reads 25, leaves '\n' in the buffer

        System.out.print("Enter your name: ");
        String name = scanner.nextLine(); // Reads the leftover '\n', not your name!

        System.out.println("Name: " + name + ", Age: " + age); // Name will be empty!

        scanner.close();
    }
}

The Solution

After reading a number with nextInt(), nextDouble(), etc., add an extra, empty scanner.nextLine(); call to consume the leftover newline character before you try to read a full line of text.

import java.util.Scanner;

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

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

        // THE FIX: Consume the leftover newline character
        scanner.nextLine();

        System.out.print("Enter your name: ");
        String name = scanner.nextLine(); // Now this works correctly!

        System.out.println("Name: " + name + ", Age: " + age);

        scanner.close();
    }
}