Different ways to read from console in Java

1) Reading through a

BufferedReader

BufferedReader class has the following methods to read

  1. int read() - reads a single char
  2. int read (char[] but, int off, int len) - reads a char into a portion of
    an array
  3. String readLine() - reads a line of text

BufferedReader object can be constructed with an InputStreamReader object.
First, we need to instantiate an InputStreamReader with a System.in
(standard input object provided by the language).

Below are the steps to create a BufferedReader object.

  1. BufferedReader buffReader;
  2. InputStreamReader inReader;
  3. inReader = new InputStreamReader(System.in);
  4. buffReader = new BufferedReader(inReader);

Shorthand way: BufferedReader buffReader = new
BufferedReader( new InputStreamReader(System.in);

Java Example code

package program;

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

public class Main {

public static void main(String[] args){

BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(System.in)
);

String line = bufferedReader.readLine();
System.out.println(line);

}

}

2) Reading through a
Scanner

This is probably the most preferred way to read from the console because
it gives you more methods to read data. You can read strings, but also you
can read different data types such as int, byte, boolean and float.

It is very simple to create a scanner object just pass the standard input
stream to its constructor.

Java Example Code

package program;
import java.util.Scanner;

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();

// reading primitive data
boolean nextBool = scanner.nextBoolean();
int nextInt = scanner.nextInt();
byte nextByte = scanner.nextByte();
long nextLong = scanner.nextLong();
float nextFloat = scanner.nextFloat();
double nextDouble = scanner.nextDouble();

System.out.println(line);
System.out.println(nextBool);
System.out.println(nextInt);
System.out.println(nextByte);
System.out.println(nextLong);
System.out.println(nextFloat);
System.out.println(nextDouble);

}
}

3) Using the

Console class

You can get the Console object from the System class with console()
method.

console() - returns a console object associated with the current Java
virtual machine if any.

It will not work in IDE. Compile and run it from cmd.exe.

Java Example Code

package program;
import java.io.Console;

public class Main {

public static void main(String[] args) {

Console console = System.console();
System.out.print("Enter your name: ");
String name = console.readLine();

System.out.println();
System.out.println("Enter your password: ");
char[] password = console.readPassword();
String str = String.valueOf(password);
System.out.println("Your Info -> " + name + " " + str );
}
}

Share this Post

Leave a Reply

Your email address will not be published. Required fields are marked *