Enter your email id to get regular update free
Your Email

How to read input from console in Java?

If you want to read input from console then are 3 methods available in Java.

Three ways for reading input from the user in the command line environment or console are:
1.Use Buffered Reader Class
2.Use Scanner Class
3.Use Console Class
Buffered Reader Class
This is the classical method to take input in Java  and it  is used by wrapping the System.in  in an InputStreamReader which is wrapped in a BufferedReader you  can read input from the user in the command line.It provides efficient reading but the wrapping code is hard to remember.
import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
public class Test
 public static void main(String[] args) throws IOException

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
 String name = reader.readLine();

Scanner Class
Scanner class parse primitive types and strings using regular expressions and it can also be used to read input from the user in the command line.Regular expressions can be used to find tokens using Scanner class but this  methods is not synchronized.
class GetInputFromUser
 public static void main(String args[])
 Scanner in = new Scanner(System.in);
 String s = in.nextLine();
 System.out.println("This is string"+s);
int a = in.nextInt();
 System.out.println("This is integer "+a);
 float b = in.nextFloat();
System.out.println("This is float "+b);
Console Class
It is used for reading password such that input without echoing the characters entered by the user and the format string syntax can also be used.Using this method  are synchronized and Format string syntax can be used but It doesn't work in non-interactive environment.
Java code for Demonstration:
public class Sample
 public static void main(String[] args)
String name=System.console().readline();
This code will not run on IDE because console class doesn't work in non interactive environment.
Read input
Tech writer at newsandstory
Total 99 views