The main method and args
Learn the entry point the JVM looks for, and read the arguments it hands you.
Open this lesson in the learning hubKey points
- The JVM starts at
public static void main(String[] args). Any other signature compiles but will not launch. - static because no object exists yet, public so the launcher can reach it, void because the exit code is separate.
argsholds whatever followed the class name on the command line. When nothing was passed it is empty, nevernull.- Every argument arrives as text, so
"7" + 1is"71". Parse it first withInteger.parseInt. - Returning from
mainexits with code 0, which means success.System.exit(1)signals failure. - Any class may declare a
main, even when it is not the entry point — handy for quick experiments.
Example
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println("real args.length = " + args.length + " -> " + Arrays.toString(args));
String[] demo = args.length > 0 ? args : new String[]{"report", "--verbose", "sales.csv"};
System.out.println("pretending you ran: java Main " + String.join(" ", demo));
String command = demo[0];
boolean verbose = false;
String file = null;
for (String arg : demo) {
if (arg.equals("--verbose")) {
verbose = true;
} else if (arg.endsWith(".csv")) {
file = arg;
}
}
System.out.println("command = " + command + ", verbose = " + verbose + ", file = " + file);
System.out.println("every argument arrives as text: \"7\" + 1 = " + ("7" + 1));
System.out.println("so numbers need parsing: 7 + 1 = " + (Integer.parseInt("7") + 1));
System.out.println("exit code would be " + (file == null ? 1 : 0) + "; 0 means success");
}
}
main is an ordinary method with the one signature the launcher recognises.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Core Java course, and every lesson in it is listed on the Core Java contents page.