Taking input from User

To interact with keyboard we need a stream. Java has three predefined streams for users


  1. System.in
  2. System.out
  3. System.err

System.in

System.in is an input stream between program and keyboard. This stream is byte stream, already provided by java. To take input from user no need to create any stream.

Program :


class inp 
{
public static void main(String arg[])
{
System.out.print("Enter data:");
int data;
do{
data=System.in.read();
System.out.print((char)data);
}while(data!='\n');
}
}


Above program is not efficient program because of time taken by it is more. "System.in" is an input byte stream, means information will flow in form of 0 and 1's. "read()" method is used to read data given by user. "read()" method will read one byte at a time. In order to read multiple bytes, "read()" need to be called multiple times.


Extension for above program is converting byte stream into character stream. System.in is an byte stream, we can't change this. All we can do is to wrap this stream by character stream.

Program :


 class inp 
{
public static void main(String arg[]) throws IOException
{
InputStreamReader ins=new InputStreamReader(System.in);
System.out.print("Enter data:");
char data[]=new char[50];
ins.read(data);
for(char c:data)
System.out.print(c);
}
}

In above program character stream is created between program and keyboard. character are flowing one by one. Still there is efficiency issue, because it's reading one character at a time.

One more extension can be added to program, provide buffer capability so that multiple character can be read in one go.

Program :


 class inp 
{
public static void main(String arg[]) throws IOException
{
InputStreamReader ins=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ins);
System.out.print("Enter data:");
String str=br.readLine();
System.out.print(str);

}
}


System.out

System.out is a stream between program and monitor. "System.out" is a byte stream. In java use of "System.out" is permissible but PrintWriter class is recommended. PrintWriter is a character stream.

Program :


 class inp 
{
public static void main(String arg[]) throws IOException
{
PrintWriter pr=new PrintWriter(System.out,true);
pr.println("Hello World");
}
}

In constructor of "PrintWriter" class. Two arguments are passed, first is output stream and second is boolean data type. Second argument specify whether java flushes stream every time new line '\n' encountered.

System.err

System.err is a byte stream for displaying error. It can be used to redirect error in a log file.