Java - Main Method

> Procedural Languages > Java

1 - About

The main in Java.

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.

Advertising

3 - 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 MyApp 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:

-descending

4 - Example

package com.gerardnico;
 
public class MyMain {
 
	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);
	}
 
}

5 - Library

To parse the command arguments, you can use the Apache Commons CLI library

lang/java/main.txt · Last modified: 2017/09/17 18:25 by gerardnico