Login
Your Email
Pasword
Home
Write
Trending
History
Liked
Dashboard

How to read input from console in Java?

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

Do you have similar website/ Product?
Show in this page just for only $2 (for a month)
Create an Ad
0/60
0/180
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();
System.out.println(name);
 }
 }

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();
 System.out.println(name);
 }
 }
This code will not run on IDE because console class doesn't work in non interactive environment.
CONTINUE READING
Read input
Console
Java
Ayesha
Tech writer at newsandstory