It is important to discuss input-output streams as it is used while implementing System.in.read()
.
io
stream we have java.io
package.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.
System
indicates the current computer system.in
indicates standard input device System.in.read
indicates 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
.
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
Input
class in Java.throws java.io.IOException
to avoid the IO exception while reading user-input.byte
class using byte b[]=new byte[50];
System.in.read(b);
String s =new String(b);
and display the output .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
Line 2: We create an Main
class in Java.
Line 6: We create the object of the byte
class using byte 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 try
block, and the type of exception is placed inside the catch
block.
Lines 14 to 16:
We convert the bytes of user input into a
string using
String s =new String(b)
and display the output.