2.2 Executable main Method, Command-Line Execution & Console Output

Key Takeaways

  • The JVM entry point requires public, static, void return type, name main, and a single String array or varargs parameter (String[] args, String args[], or String... args)

  • A method named main with an ineligible signature can compile as an ordinary method. The Java 8 launcher rejects the class if it cannot find an eligible entry method.

  • Use javac with the .java extension to compile and java with the fully qualified class name (no .class extension) to execute

  • Command-line arguments start at args[0]—the class name is never included—and invoking java with zero arguments passes a non-null empty array (args.length == 0)

  • System.out.printf and System.out.format support specifiers like %s, %d, %f, and %n, throwing IllegalFormatConversionException at runtime if an argument type is incompatible with %d or %f

Last updated: November 2026

Executable main Method, Command-Line Execution & Console Output

Running a Java program from a terminal exposes several subtle rules that frequently appear in 1Z0-808 questions: which variations of main the JVM accepts, what happens when you pass .class to the java launcher, how args handles missing or quoted arguments, and how System.out.printf formats output.

Valid vs. Invalid main Method Signatures

To run a Java 8 application from the command line, the launcher needs an entry method with these exact characteristics:

  • Access modifier: public
  • Non-access modifier: static (may swap order: static public)
  • Return type: void (must appear immediately before main)
  • Method name: main (lowercase)
  • Single parameter: An array of String (String[] args, String args[], String []args) or String varargs (String... args), using any valid parameter name
  • Optional legal modifiers: final, strictfp, and synchronized are permitted

Important

An invalid main signature usually compiles without error! The compiler treats public static void main(String args) or public int main(String[] args) as an ordinary or overloaded method. If the class has no eligible entry method, the launcher reports an error before entering application code.

Candidate SignatureCompiles?JVM Entry Point?Notes
public static void main(String[] args)YesYesCanonical signature
static public final void main(String... cmd)YesYesModifier order swapped; final and varargs allowed
public static void main(String argv[])YesYesC-style array brackets on parameter name are valid
static void main(String[] args)YesNoPackage-private; lacks public
public void main(String[] args)YesNoInstance method; lacks static
public static int main(String[] args)YesNoReturn type must be void
public static void main(String args)YesNoParameter is a single String, not String[]
public void static main(String[] args)NoNoReturn type void must immediately precede method name

A class may also overload main with multiple signatures—such as public static void main(String[] args) alongside public static void main(int count). Both compile, and the JVM invokes only the String[] (or String...) entry point.

Compiling with javac and Running with java

Two command-line tools handle building and launching Java SE 8 applications:

  • javac (Compiler): Accepts .java file paths and produces .class bytecode files.
  • java (Launcher): In class-launch mode, use the fully qualified class name without a filename extension. Java 8 can also launch an executable JAR with java -jar app.jar.

Consider a source file src/app/EchoArgs.java belonging to package app;:

# Create the output directory, then compile out/app/EchoArgs.class
mkdir -p out
javac -d out src/app/EchoArgs.java

# Run by specifying classpath (-cp) and fully qualified class name
java -cp out app.EchoArgs alpha "beta gamma" 42

Key command-line flags and pitfalls tested on the exam:

  1. Using -d with javac: The -d <dir> option tells javac where to place generated .class files, automatically creating subdirectories matching the package declaration. The target root directory (out) must already exist, though javac creates the package subfolders (app/) automatically.
  2. No .class extension on java: Running java -cp out app.EchoArgs.class fails because the launcher treats .class as part of the class name and cannot load a class under that name.
  3. Classpath (-cp or -classpath): Tells javac and java where to find user classes and JARs. If -cp is omitted and CLASSPATH is unset, the default user class path is the current directory (.). When you specify -cp lib/helper.jar, the current directory is no longer searched unless you explicitly include . (e.g., -cp .:lib/helper.jar on macOS/Linux or -cp .;lib/helper.jar on Windows).

How Command-Line args Behaves

Unlike C or C++, Java does not put the program or class name into args[0]. Every element in args is an argument passed after the class name.

package app;

public class EchoArgs {
    public static void main(String... args) {
        System.out.println("Count: " + args.length);
        for (int i = 0; i < args.length; i++) {
            System.out.println(i + ": [" + args[i] + "]");
        }
    }
}

Trace three different invocations of EchoArgs:

Commandargs.lengthargs[0]args[1]
java -cp out app.EchoArgs0throws ArrayIndexOutOfBoundsExceptionN/A
java -cp out app.EchoArgs one two2"one""two"
java -cp out app.EchoArgs "one two" 992"one two""99"

Two critical facts to remember:

  • Empty array, never null: When no arguments are supplied, the JVM creates a zero-length array (new String[0]). args == null is false, while accessing args[0] throws ArrayIndexOutOfBoundsException.
  • All elements are String: Even 99 arrives as the String "99". Arithmetic requires parsing via Integer.parseInt(args[1]) or Double.parseDouble(...).

Console Output: print, println, printf, and format

System.out is a java.io.PrintStream object initialized by the JVM for standard output. Its output methods fall into two groups:

  • print(value): Writes the string representation of value with no trailing line break. Calling System.out.print() with zero arguments does not compile.
  • println(value) and println(): Writes value followed by the platform line separator. Calling System.out.println() with zero arguments is legal and prints a blank line.
  • printf(format, args...) and format(format, args...): Identical formatted-output methods that parse format specifiers and return this (PrintStream).

Common format specifiers for printf / format:

SpecifierAccepted TypesBehavior & Example
%sAny type (null -> "null")Uses Formattable.formatTo for a Formattable argument, otherwise toString() for a non-null argument
%dIntegral (byte, short, int, long, BigInteger)Decimal integer (%04d pads 7 to 0007)
%fFloating-point (float, double, BigDecimal)Decimal float; defaults to 6 decimal places (%.2f -> 12.35)
%bAny (null -> false, non-boolean non-null -> true)Boolean output (true / false)
%nNone (takes no argument)Platform-specific line separator
%%None (takes no argument)Literal % character
public class FormatCheck {
    public static void main(String[] args) {
        System.out.print("A");
        System.out.println("B");
        System.out.printf(java.util.Locale.ROOT, "Item: %-6s Qty: %03d Price: %.2f%n", "Pen", 4, 1.5);
        // System.out.printf("%d", 1.5); // Compiles, throws IllegalFormatConversionException!
    }
}

Output:

AB
Item: Pen    Qty: 004 Price: 1.50

Notice the runtime trap in the commented line: passing a double (1.5) to %d or an int (4) to %f compiles cleanly because printf accepts Object..., then throws java.util.IllegalFormatConversionException at runtime.

Test Your Knowledge

Given the file Launcher.java below, what happens when you compile with javac Launcher.java and run with java Launcher?

public class Launcher {
    public static void main(String args) {
        System.out.println("String");
    }
    static void main(String[] args) {
        System.out.println("Array");
    }
}
A

Compilation fails because main cannot be overloaded

B

It compiles, then the Java launcher rejects the class because neither method is an eligible entry point

C

It compiles and prints Array

D

It compiles and prints String

Test Your Knowledge

Suppose Echo.java compiles cleanly without a package declaration:

public class Echo {
    public static void main(String... inputs) {
        System.out.println(inputs.length + ":" + inputs[0]);
    }
}

What happens when you execute java Echo with no extra arguments?

A

It prints 1:Echo

B

It prints 0:null

C

It throws NullPointerException

D

It throws ArrayIndexOutOfBoundsException

Test Your Knowledge

What is the result of compiling and running the following code?

public class ConsoleMix {
    public static void main(String[] args) {
        System.out.print("X");
        System.out.printf(java.util.Locale.ROOT, "%s-%d-%.1f%n", 10, 20, 3.46);
    }
}
A

It prints X10-20-3.5 followed by a newline

B

It throws IllegalFormatConversionException because 10 is an int passed to %s

C

It prints X10-20-3.4 followed by a newline

D

Compilation fails because printf requires a String for %s

Sections you finish are checked off in the contents.