Input / output

Input and output (I/O) operations in Java allow a program to interact with users by receiving inputs and displaying outputs. Java provides various classes and methods to handle I/O through the console.

Input in Java

Using Scanner Class

The Scanner class is part of the java.util package and is commonly used to read input from the user through the console.

Example

To use the Scanner class, you first need to import it:

import java.util.Scanner;

Reading Different Types of Input

import java.util.Scanner;

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

        // Reading a string input
        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        System.out.println("Hello, " + name + "!");

        // Reading an integer input
        System.out.print("Enter your age: ");
        int age = scanner.nextInt();
        System.out.println("You are " + age + " years old.");

        // Reading a double input
        System.out.print("Enter your height in meters: ");
        double height = scanner.nextDouble();
        System.out.println("You are " + height + " meters tall.");

        scanner.close();
    }
}

Common Methods of Scanner

  • nextLine(): Reads a line of text.
  • next(): Reads a single word.
  • nextInt(): Reads an integer.
  • nextDouble(): Reads a double.
  • nextBoolean(): Reads a boolean.

Using BufferedReader and InputStreamReader

The BufferedReader and InputStreamReader classes can also be used for input. This method is less common but can be more efficient for reading large amounts of data.

Example

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        // Reading a string input
        System.out.print("Enter your name: ");
        String name = reader.readLine();
        System.out.println("Hello, " + name + "!");

        // Reading an integer input
        System.out.print("Enter your age: ");
        int age = Integer.parseInt(reader.readLine());
        System.out.println("You are " + age + " years old.");

        // Reading a double input
        System.out.print("Enter your height in meters: ");
        double height = Double.parseDouble(reader.readLine());
        System.out.println("You are " + height + " meters tall.");
    }
}

Output in Java

Using System.out.print and System.out.println

The System.out object is used to output text to the console. The print method outputs text without a newline, whereas the println method outputs text followed by a newline.

Example

public class Main {
    public static void main(String[] args) {
        System.out.print("This is a ");
        System.out.print("single line.");
        
        System.out.println("This is a new line.");
        System.out.println("This is another line.");
    }
}

Using printf for Formatted Output

The printf method provides a way to format strings. It works similarly to the printf function in C.

Example

public class Main {
    public static void main(String[] args) {
        String name = "Alice";
        int age = 30;
        double height = 1.75;

        System.out.printf("Name: %s\n", name);
        System.out.printf("Age: %d\n", age);
        System.out.printf("Height: %.2f meters\n", height);
    }
}

Format Specifiers

  • %s: String
  • %d: Decimal integer
  • %f: Floating-point number
  • %c: Character
  • %b: Boolean

Combining Input and Output

Combining input and output operations allows for interactive programs where user input is used to generate output.

Example

import java.util.Scanner;

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

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();
        System.out.println("Hello, " + name + "!");

        System.out.print("Enter a number: ");
        int number = scanner.nextInt();
        System.out.printf("The square of %d is %d.\n", number, number * number);

        scanner.close();
    }
}

Best Practices

Input and output (I/O) operations in Java allow a program to interact with users by receiving inputs and displaying outputs. Java provides various classes and methods to handle I/O through the console.

Best Practices

  1. Close the Scanner: Always close the Scanner object when it’s no longer needed to free up resources.
  2. Handle Exceptions: Be prepared to handle exceptions, especially when dealing with numeric input that might cause InputMismatchException.
  3. Validate Input: Validate user input to ensure it meets expected formats and ranges.