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
mainwith 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
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 beforemain) - Method name:
main(lowercase) - Single parameter: An array of
String(String[] args,String args[],String []args) orStringvarargs (String... args), using any valid parameter name - Optional legal modifiers:
final,strictfp, andsynchronizedare 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 Signature | Compiles? | JVM Entry Point? | Notes |
|---|---|---|---|
public static void main(String[] args) | Yes | Yes | Canonical signature |
static public final void main(String... cmd) | Yes | Yes | Modifier order swapped; final and varargs allowed |
public static void main(String argv[]) | Yes | Yes | C-style array brackets on parameter name are valid |
static void main(String[] args) | Yes | No | Package-private; lacks public |
public void main(String[] args) | Yes | No | Instance method; lacks static |
public static int main(String[] args) | Yes | No | Return type must be void |
public static void main(String args) | Yes | No | Parameter is a single String, not String[] |
public void static main(String[] args) | No | No | Return 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.javafile paths and produces.classbytecode 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 withjava -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:
- Using
-dwithjavac: The-d <dir>option tellsjavacwhere to place generated.classfiles, automatically creating subdirectories matching thepackagedeclaration. The target root directory (out) must already exist, thoughjavaccreates the package subfolders (app/) automatically. - No
.classextension onjava: Runningjava -cp out app.EchoArgs.classfails because the launcher treats.classas part of the class name and cannot load a class under that name. - Classpath (
-cpor-classpath): Tellsjavacandjavawhere to find user classes and JARs. If-cpis omitted andCLASSPATHis 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.jaron macOS/Linux or-cp .;lib/helper.jaron 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:
| Command | args.length | args[0] | args[1] |
|---|---|---|---|
java -cp out app.EchoArgs | 0 | throws ArrayIndexOutOfBoundsException | N/A |
java -cp out app.EchoArgs one two | 2 | "one" | "two" |
java -cp out app.EchoArgs "one two" 99 | 2 | "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 == nullisfalse, while accessingargs[0]throwsArrayIndexOutOfBoundsException. - All elements are
String: Even99arrives as theString"99". Arithmetic requires parsing viaInteger.parseInt(args[1])orDouble.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 ofvaluewith no trailing line break. CallingSystem.out.print()with zero arguments does not compile.println(value)andprintln(): Writesvaluefollowed by the platform line separator. CallingSystem.out.println()with zero arguments is legal and prints a blank line.printf(format, args...)andformat(format, args...): Identical formatted-output methods that parseformatspecifiers and returnthis(PrintStream).
Common format specifiers for printf / format:
| Specifier | Accepted Types | Behavior & Example |
|---|---|---|
%s | Any type (null -> "null") | Uses Formattable.formatTo for a Formattable argument, otherwise toString() for a non-null argument |
%d | Integral (byte, short, int, long, BigInteger) | Decimal integer (%04d pads 7 to 0007) |
%f | Floating-point (float, double, BigDecimal) | Decimal float; defaults to 6 decimal places (%.2f -> 12.35) |
%b | Any (null -> false, non-boolean non-null -> true) | Boolean output (true / false) |
%n | None (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.
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");
}
}
Compilation fails because main cannot be overloaded
It compiles, then the Java launcher rejects the class because neither method is an eligible entry point
It compiles and prints Array
It compiles and prints String
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?
It prints 1:Echo
It prints 0:null
It throws NullPointerException
It throws ArrayIndexOutOfBoundsException
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);
}
}
It prints X10-20-3.5 followed by a newline
It throws IllegalFormatConversionException because 10 is an int passed to %s
It prints X10-20-3.4 followed by a newline
Compilation fails because printf requires a String for %s
Sections you finish are checked off in the contents.