OCP exam prep: the main method¶
☕ Java 17 · 🎓 OCP 1Z0-829 · Writing Your First main() Method
Optional page
This page is for readers preparing the Oracle Certified Professional Java SE 17 Developer exam (1Z0-829). The concepts are all you need otherwise.
Four traps to watch for¶
Trap 1 — Compiles ≠ runs
A class with a wrong main (no static, int return type, wrong parameter) or no main at all compiles. The error only appears when the JVM tries to launch it.
Trap 2 — String[] and String... are both valid
public static void main(String... args) is a valid entry point. So is any parameter name.
Trap 3 — Modifier order doesn't matter
static public void main(String[] args) is as valid as public static void main(String[] args).
Trap 4 — args[0] without arguments
It compiles, then throws ArrayIndexOutOfBoundsException at runtime when no argument is passed. args is never null: it's an empty array.
Practice questions¶
1. Which are valid entry points? (Choose all that apply.)
A. public static void main(String[] args) { }
B. public static void main(String... args) { }
C. public static int main(String[] args) { return 0; }
D. static public void main(String[] args) { }
Answer
A, B and D. Varargs is equivalent to String[], and public/static can be swapped. C returns int: it compiles, but the JVM won't use it as the entry point.
2. What happens with java NetflixLauncher (no arguments)?
public class NetflixLauncher {
public static void main(String[] args) {
System.out.println("Platform: " + args[0]);
}
}
A. Compilation error
B. Prints Platform: null
C. ArrayIndexOutOfBoundsException at runtime
D. Prints Platform:
Answer
C. args[0] is valid syntax, so it compiles. With no arguments, args is empty and index 0 doesn't exist.