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 sourcekeyboard to a Java program.
  • Output-stream means writing-streams. It writes the data from the Java program and displays datamonitors.
  • To work with the io stream we have java.io package.

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.

  • 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.

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 Input class in Java.
  • Line 3: We use the throws java.io.IOException to avoid the IO exception while reading user-input.
  • Line 5: We create the object of the byte class using byte 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 string
System.out.println(s);
}
}

Enter the input below

Explanation

  • 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.

Free Resources