Command Line Input in Java



So far we have been using only the Command Line Ouput System.out.println to display and message on console. Java also has a method for console input. We will now show how to get Console Input.

  1. /*
  2.   ReferenceDesigner.com Java Tutorial
  3.   Understanding Console Input InputStreamReader
  4.   */
  5.  
  6. import java.io.BufferedReader;
  7. import java.io.IOException;
  8. import java.io.InputStreamReader;
  9.  
  10. class readname {
  11. public static void main(String[] args) {
  12.  
  13. System.out.print("What is your name : ");
  14.  
  15. try{
  16. BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
  17. String name = bufferRead.readLine();
  18. System.out.println();
  19. System.out.println("Hello "+name);
  20. }
  21. catch(IOException e)
  22. {
  23. e.printStackTrace();
  24. }
  25.  
  26. }
  27. }


If you compile and run, it prompts you and awaits for your response. Once you enter a complete line It responds back with hi yourname


 What is your name : Michael

Hello Michael