Input from the terminal in Java

The main method has a mechanism to accept input when run from the terminal.


Run from terminal

Let’s say I have this class

This code is saved in file under my desktop. In order to run it from the terminal, I will need to navigate with my terminal to my desktop and execute these commands:

javac — to compile the source code into java byte code.

java Main — to run without any arguments.

Run from the terminal with arguments

Now, I have a little different code. The main method has String[] argument. Basically, when running the code from the terminal we pass data for this argument.


java Main John — run with one argument. The above code will print hello, John . After the name of the class name, we can list arguments separated by a space. Each argument will be assigned to a string array.

Let’s see another example


If we want to combine two separate words as one argument, we can use double-quotes.


Software Developer, Java Instructor

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store