In order to get inputs from the keyboard we can use standard input stream (System.in ) available in the java.lang package. Generally standard input stream contains byte stream coming from the keyboard. Of cause we can change the standard input. In this example I have used an InputStreamReader object to read the input stream. Lets see a simple java program written to demonstrate how to get keyboard inputs in java.
//© learnjavaapi.blogspot.com
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class GetInput{
public static void main(String args[]) throws IOException{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.print("Please Enter your name : ");
String name=br.readLine();
System.out.println("Hi "+ name +" how are you ? ");
in.close();
br.close();
}
}
Output :
Let me explain important parts of this program.
In the first three lines I have imported essential classes. By using
throws keyword I have thrown
IOException from my program. So all input/output exceptions are ignored in our program. By creating
InputStreamReader object called
in our program is ready to get keyboard inputs. For better input handling
BufferedReader object br is used. This joining is called wrapping InputStreamReader object within BufferedReader object. InputStreamReader reads bytes from the input stream and decodes them into characters.
JavaDoc: