System.in.read example

As known System.in is Standard Input stream in Java,
System is a class in java.lang package(this is the package imported by all Java programs, by default),
in is object of type InputStream
read() is method, to read from the input stream, in this case Standard Input Stream

Below is an example on how to use System.in.read()

import java.io.IOException;

public class systeminread {
public static void main(String args[]) throws IOException
{
int i;

//read one character from keyboard
i = System.in.read();

System.out.println((char)i);

byte bt[] = new byte[20];

//read multiple characters from keyboard into byte array
System.in.read(bt);

//convert byte array to String
String str = new String(bt);

//trim the String to remove whitespaces at the end, if any
str = str.trim();

System.out.println(str);
}
}

Leave a Reply