About
This page is about the main method in Java (ie the startup point of every app).
Example
This is a quick example that shows how to write a main method.
IDE may create it for you via template if you write the short notation psvm followed by a tab
package com.datacadamia.myapp;
public class MyMain {
// the main method that is called from the command line with the arguments args
public static void main(String[] args) throws Exception {
// The local variables
String myFirstParameter = null;
boolean printTrue = false;
// Treatment of the args parameters
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("-printTrue")) {
printTrue = true;
} else if (args[i].equals("-usage")) {
usage();
} else if (args[i].equals("-help")) {
usage();
} else {
myFirstParameter = args[i];
// Must be last arg
if (i != args.length - 1) {
usage();
}
}
}
// Last usage verification
if (myFirstParameter == null) {
usage();
}
// The actions to performed by the application
System.err.println("FirstParameter: " + myFirstParameter);
if (printTrue) {
System.err.println("True");
}
}
private static void usage() {
System.err.println("Usage: MyMain [-options] <myFirstParameter>");
System.err.println(" -printTrue = print the word true");
System.err.println(" -usage or -help = this message");
System.exit(1);
}
}
How to write a main method?
In the Java programming language, every application must contain a main method whose signature is:
public static void main(String[] args)
The main method accepts a single parameter, usually named args, whose type is an array of String objects.
The public static void keywords mean:
- the Java virtual machine (JVM) interpreter can call the method to start the program (public) without creating an instance of the class (static),
- the program does not return data to the Java VM interpreter (void) when it ends.
The modifiers public and static can be written in either order (public static or static public), but the convention is to use public static as shown above.
The argument
You can name the argument anything you want, but most programmers choose “args” or “argv”.
The main method accepts a single argument: an array of elements of type String.
This array is the mechanism through which the runtime system passes information to your application. For example:
java -jar MyApp.jar arg1 arg2
Each string in the array is called a command-line argument.
For example, a sorting program might allow the user to specify that the data be sorted in descending order with this command-line argument:
java -jar MyApp.jar -descending
Library
To parse the command arguments, you can use the Apache Commons CLI library