Command Line
Command Line Arguments
It is possible to run a Java program from the command line like this:
> java taylor.FishingGame
Here the FishingGame
class in the taylor
package must be the
entry point for the program (contains the main()
method).
Suppose I wanted to be able to specify the level that the game starts on when I run the program. For example,
> java taylor.FishingGame 3
should start the fishing game on level 3 (it turns out the first two levels are boring).
Java allows us to specify an arbitrary number of command line arguments
after the class containing the main()
method. These arguments are
passed to the main()
method as an array of strings. Recall that the
main()
method looks like this:
public static void main(String[] args) {
// ...
}
The args
array contains the command line arguments. In this particular
example, the array contains one element: {"3"}
. Here are some other examples:
Command line | Value of args |
---|---|
java taylor.FishingGame 3 Chris Taylor | {"3", "Chris", "Taylor"} |
java taylor.FishingGame 3 "Chris Taylor" | {"3", "Chris Taylor"} |
Command Line Arguments with Jar Files
Specifying command line arguments is very similar when running an
executable .jar
file:
> java -jar FishingGame.jar 3
Specifying Command Line Arguments in IntelliJ
When running a program in IntelliJ, you can specify the command line argument(s) in the run configuration. To do this,
- Load the class with the
main()
method in the IntelliJ text editor - Right-click in the text area and select Run 'FishingGame.main()' (1 in the figure below)
- Click on FishingGame to the right of the Run icon (2 in the figure below)
- Select Edit Configurations
- Add the desired argument(s) in the Program Arguments box
Now, whenever you run this configuration, it will supply the program arguments to the program so that you don't have to retype them each time you run your program.
Command Line Arguments in JavaFX
JavaFX provides additional support for command line arguments. The application
class has a
getParameters()
method that returns an
Application.Parameters
object. Note: this is an instance method, so you'll need to call it in an
instance method, e.g., start(Stage stage)
.
Take a look at the
Application.Parameters
class for details on how to access the command line arguments.