Course Content
Core Java
About Lesson

Keyboard inputs can be read through multiple ways.

  1. Scanner class
  2. BufferedReader class
  3. Console class

Scanner

It is provided in the java.util package. It is powerful for parsing input into tokens. It’s commonly used for reading input from various sources, including the keyboard, files, and streams.

Scanner class provides methods for reading input of different data types, such as strings, integers, floats, doubles, etc. Methods like nextInt(), nextFloat(), nextDouble(), etc., parse the input into the specified data type.

By default, the Scanner class uses whitespace as the delimiter to separate tokens. You can customize the delimiter using the useDelimiter() method to specify a custom pattern for token separation.

The Scanner class can read input from different sources, including System.in for keyboard input, files, strings, and streams.

After using the Scanner object, it’s essential to close it using the close**()** method to release system resources. Failure to close the Scanner may lead to resource leaks and inefficient memory usage.

Code to get int inputs from keyboard and calculate sum

import java.util.Scanner;

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

        System.out.print("Enter first number: ");
        int num1 = scanner.nextInt();

        System.out.print("Enter second number: ");
        int num2 = scanner.nextInt();

        int sum = num1 + num2;
        System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);

        scanner.close();
    }
}

Update delimiter from space to ;


    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        
        scanner.useDelimiter(";"); 

        System.out.print("Enter the numbers separated by semicolon: ");
        int num1 = scanner.nextInt();
        int num2 = scanner.nextInt();

        int sum = num1 + num2;
        System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);

        scanner.close();
    }

Some common methods

boolean hasNextBoolean() Returns true if the next value entered by the user is a valid boolean value.
boolean hasNextByte() Returns true if the next value entered by the user is a valid byte value.
boolean hasNextDouble() Returns true if the next value entered by the user is a valid double value.
boolean hasNextFloat() Returns true if the next value entered by the user is a valid float value.
boolean hasNextInt() Returns true if the next value entered by the user is a valid int value.
boolean hasNextLong() Returns true if the next value entered by the user is a valid long value.
boolean hasNextShort() Returns true if the next value entered by the user is a valid short value
boolean nextBoolean() Reads a boolean value from the user.
byte nextByte() Reads a byte value from the user.
double nextDouble() Reads a double value from the user.
float nextFloat() Reads a float value from the user.
int nextInt() Reads an int value from the user.
String nextLine() Reads a String value from the user.
long nextLong() Reads a long value from the user.
short nextShort() Reads a short value from the user.

BufferedReader

It is also a class which provides a way to read input from the console (keyboard). This method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line.

It is efficient for reading large amounts of text due to buffering mechanisms. Use BufferedReader when efficiency is a priority or when reading large amounts of text. Close the BufferedReader object after use to release system resources.

It does not provide delimiter-based tokenization.

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

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

        try {
            // Input first operand
            System.out.print("Enter the first operand: ");
            String operand1Input = reader.readLine();
            double operand1 = Double.parseDouble(operand1Input);

            // Input second operand
            System.out.print("Enter the second operand: ");
            String operand2Input = reader.readLine();
            double operand2 = Double.parseDouble(operand2Input);

            // Perform subtraction
            double result = operand1 - operand2;

            // Display result
            System.out.println("Result of subtraction: " + result);
        } catch (IOException e) {
            System.err.println("Error reading input: " + e.getMessage());
        } catch (NumberFormatException e) {
            System.err.println("Invalid input format. Please enter numeric values.");
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                System.err.println("Error closing BufferedReader: " + e.getMessage());
            }
        }
    }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

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

        try {
            // Input first operand
            System.out.print("Enter the first operand: ");
            String operand1Input = readLineWithEcho(reader);
            double operand1 = Double.parseDouble(operand1Input);

            // Input second operand
            System.out.print("Enter the second operand: ");
            String operand2Input = readLineWithEcho(reader);
            double operand2 = Double.parseDouble(operand2Input);

            // Perform subtraction
            double result = operand1 - operand2;

            // Display result
            System.out.println("Result of subtraction: " + result);
        } catch (IOException e) {
            System.err.println("Error reading input: " + e.getMessage());
        } catch (NumberFormatException e) {
            System.err.println("Invalid input format. Please enter numeric values.");
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                System.err.println("Error closing BufferedReader: " + e.getMessage());
            }
        }
    }

    private static String readLineWithEcho(BufferedReader reader) throws IOException {
        StringBuilder sb = new StringBuilder();
        int c;
        while ((c = reader.read()) != '\n' && c != -1) {
            System.out.print((char) c);
            sb.append((char) c);
        }
        return sb.toString().trim(); // Trim leading and trailing whitespace
    }
}

Console

The Console class in Java provides methods to interact with the console, including reading input from the keyboard and printing output. It offers functionalities that are particularly useful for console-based applications, such as command-line tools and interactive text-based programs.

To use the Console class, you need to obtain a Console object, which represents the system’s console:

Console console = System.console();

Reading Input:

The Console class provides methods for reading input from the console:

  • readLine(String prompt): Reads a line of text from the console, displaying the specified prompt.
  • **r**eadPassword(String prompt): Reads a password from the console without echoing characters to the screen.

Printing Output:

The Console class provides methods for printing output to the console:

  • printf(String format, Object... args): Formats and prints a string to the console using the specified format.
  • format(String format, Object... args): Similar to printf(), formats and prints a string to the console.
import java.io.Console;

public class ConsoleExample {
    public static void main(String[] args) {
                Console console = System.console();
        if (console != null) {
            String username = console.readLine("Enter username: ");
            char[] password = console.readPassword("Enter password: ");
            console.printf("Hello, %s!%n", username);
            console.printf("Password is %s %n", new String(password));
        } else {
            System.out.println("Console is not available.");
        }
    }
}

The Console class is available only in console-based environments. If the application is run in an environment without a console (e.g., in an IDE or as a background service), System.console() returns null. The Console class is not suitable for GUI-based applications or scenarios where console interaction is not required.

A Console-based environment refers to a computing environment where interaction between the user and the computer occurs primarily through a text-based interface, typically via a command-line interface (CLI) or a terminal window. In such environments, users interact with the system by typing commands and receiving textual output, without the need for graphical user interfaces (GUIs) or pointing devices like mouse.

Now a days console-based environments are often emulated through terminal emulator applications. Terminal emulators provide a graphical interface that simulates a console environment, allowing users to interact with command-line-based programs and utilities. Examples: GNOME Terminal, Konsole, PuTTY, and macOS Terminal.

Scroll to Top