There are multiple ways of handling inputs from the user, they are discussed below.
System.in
The System.in
is a static InputStream
. It is an instance of InputStream
and is predefined in the System
class, so you can use it without instantiating a new InputStream
object.
(This is similar to System.out
). The System.in
reads bytes; does not provide methods for parsing text or numbers directly.
public static final InputStream in = null;
public calss Demo {
public static void main(String[] args) throws IOException {
System.out.println("Enter a numebr: ");
int num = System.in.read();
System.out.println(num);
}
}
Enter a number:
5
53
The System.in
gives the ASCII value of the user input, and it reads one character at a time. To allow reading a string you will have to use a loop to allow the System.in
to read the entire string.
BufferReader
BufferReader
is a specialised class works with IO. The BufferReader
often used in conjunction with InputStreamReader
and the InputStreamReader
constructor requires a InputStream
object.
The BufferReader
can take input from different sources such as files by changing the constructor parameter.
public calss Demo {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a number:");
int num = Integer.parseInt(br.readLien()); //readLine() returns a string
System.out.println(num);
br.close(); // alaways good to close resources
}
}
Enter a number:
55
55
BufferReader
is a resource, therefore you will want to close it when you no longer need it to prevent resource leak.
Scanner
Scanner is a convenient way of accepting input. You pass the System.in
to the constructor to indicate you would like it to read user console input. Scanner also support reading inputs from files.
public calss Demo {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a number:");
int num = sc.nextInt();
System.out.println(num);
}
}
Enter a number:
66
66
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_Development Programming_Languages Java InputStream BufferReader Scanner