I think you have already noticed the unusual header for the main method in Java, which has the parameter args of String[]
type. Obviously, args
is an array of String. The main
method is just like a regular method in Java, you can call it by passing actual parameters to it. So let’s look at the below examples, this main method in TestMain
is invoked by a method in A
:
public class TestMain { public static void main(String[] args) { for (int i = 0; i < args.length; i++) System.out.println(args[i]); } }
public class A { public static void main(String[] args) { String[] strings = {"New York","Boston", "Atlanta"}; TestMain.main(strings); } }
The main
method is just like a regular method. Furthermore, you can pass arguments to it from the command line.
Let me show you how to display the parameters we passed to the main method from the command line:
public class CommandLineArgumentsDemo { public static void main(String[] args) { for (String arg : args) { System.out.println(arg); } } }
For the CommandLineArgumentsDemo
method, we do two steps to show the parameters we passed to it from the command line.
- use
javac
command to compile it toTestMain.class
file - use
java
command to runTestMain: java TestMain 1 2 3
The program above should display the parameters you passed to it on the console.
andrews-mbp:src andrew$ java CommandLineArgumentsDemo 1 2 3 1 2 3