How to Use System.in in Java

  • google plus

In Brief...

At times you might need to read console input provided by the user from the keyboard. The System.in field permits you to read input from the keyboard. The input can be converted into a stream of characters and then buffered so that all characters up to but not including the Enter key can be presented to the program. To learn how to use System.in in Java, follow these four steps.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  1. Open your text editor and type in the following Java statements:Java Source for System.inThe program creates an InputStreamReader object with System.in as the constructor parameter. System.in provides the input stream from the keyboard and InputStreamReader reads the stream. Next, a BufferedReader object is instantiated with the InputStreamReader object passed to the constructor. The BufferedReader object will buffer the input so that a line of text provided by the user is available to the program. The line of input is read using the readLine method. This method can potentially throw the checked exception IOException, so the method call must be in a try catch block.
  2. Save your file as UseSystemIn.java.
  3. Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter.Compile Source for System.in
  4. Type in the command to run your program and hit Enter.Run System.inAt the prompt you can type your name and then hit Enter. The readLine provides the string data to the program. The program then displays your name, and this action verifies that the data was transferred to your program successfully.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss