What is System.in.read()?
Overview
It is important to discuss input-output streams as it is used while implementing System.in.read().
- The flow of data from source to destination is the stream.
- Input-stream is reading streams. It reads data from
to a Java program.source keyboard - Output-stream means writing-streams. It writes the data from the Java program and displays
.data monitors - To work with the
iostream we havejava.iopackage.
Syntax
System.in.read(byte[])
System is a class in java.lang package.in is a static data member in the system class of type input stream class. Input stream class belongs java.io package. read byte[] is available in the input stream class.
Systemindicates the current computer system.inindicates standard input deviceSystem.in.readindicates reading from a standard input device.
Note:
- It is compulsory to use
read(byte[])of input stream-class try-catch because it throws a checked exception IOexception.- So, an alternative instead of try-catch is using
throws java.io.IOException.
Using throws
Let’s look at the code below:
class Input{public static void main(String args[])throws java.io.IOException{byte b[]=new byte[50];System.in.read(b);String s =new String(b);System.out.println(s);}}
Enter the input below
Explanation
- Line 1: We create an
Inputclass in Java. - Line 3: We use the
throws java.io.IOExceptionto avoid the IO exception while reading user-input. - Line 5: We create the object of the
byteclass usingbyte b[]=new byte[50]; - Line 6: We read the user-input using
System.in.read(b); - Lines 7 and 8: We convert the bytes of user input into a
string using
String s =new String(b);and display the output .
Using try-catch block
Let’s look at the code below:
import java.io.IOException;class Main{public static void main(String args[]){byte b[]=new byte[50];try{System.in.read(b);}catch(IOException ioe){System.out.println(ioe);}String s=new String(b);// Converts byte into stringSystem.out.println(s);}}
Enter the input below
Explanation
-
Line 2: We create an
Mainclass in Java. -
Line 6: We create the object of the
byteclass usingbyte b[]=new byte[50]; -
Lines 7 to 10: We read the user-input using
System.in.read(b);using a try-block. -
Lines 10 to 12:The program where the exception occurs is placed in the
tryblock, and the type of exception is placed inside thecatchblock. -
Lines 14 to 16: We convert the bytes of user input into a string using
String s =new String(b)and display the output.