To create an application that can be run in Java, the first requirement is that we have to create a class that contains the main() method with an array of String parameters.
For example:
The main() method must satisfy the following conditions:
- This method must be a public and static method.
- The name of this method must be main.
- The return value of this method must be void.
- This method only contains a single parameter, which is an array of String.
We can also use String … to define the parameters of the main() method. The example above can be modified as follows:
The variable name of the parameter can be set by any name.
The position of the two public and static keywords can be interchangeable, which means that the following code is still valid.
Once you have the application executable, now how to run the application and pass the value of the String array into our application. There are 2 ways to do that:
- Run the application using the IDE
- Run the application using the command line.
But first, we will modify our application so that we can print out the value of the String array that we pass on.
Using the command line
After compiling the class, we can use the command line to run our application with the following syntax:
1 |
java com.huongdanjava.Student Khanh 30 |
with:
- Java is the command of Java.
- com.huongdanjava.Student is the main class of our application.
- Khanh and 30 are elements of the array that we pass on.
For example:
Using the IDE
Depending on the IDE you are using, there are different ways to run, here are instructions on running the Spring Tool Suite IDE.
Right-click on the main class that you want to run, select Run As, and then select Java Application.
At this point, our application will fail:
1 2 |
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at com.huongdanjava.Student.main(Student.java:6) |
That’s because we have not passed the value of the parameter. To do this, run our application again as follows:
- Right-click on our main class then select Run As, then choose Run Configurations …
- At this point, we will see the Run Configurations window as follows:
- Now select the Arguments tab and enter the value of the parameters in the Program arguments box as follows:
Now you can hit the Run button to run our application.
Result: