Java Program Structure
Context: FIT2099_MOC · the skeleton every Java program shares · the entry point that runs a class · statically typed
Quick Revision
- 🎯 Objective: recognise the mandatory anatomy of a Java program ➔ a public class (named like its file) with a main entry point.
- ⚡ Key Constraint:
mainmust bepublic static void main(String[] args)—staticlets the JVM call it without creating an object first; every statement ends in;.
📝 Core
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}public➔ visibility — this member is callable from outside the class (see clients).HelloWorld➔ the class name must match the file name (HelloWorld.java).main(...)➔ the program’s entry point;String[] argsare command-line arguments (java HelloWorld arg1 arg2).static➔ the JVM callsmainwithout an object (before any instance exists).void➔ the return type “nothing”;System.out.printlnprints to the console.;➔ Java is strict — every statement ends with a semicolon.
⚠️ Common Mistakes
- 💡 File name ≠ class name = won’t compile ➔ a
publicclass must live in a file of the same name. - 💡 Non-static
main= JVM can’t start it ➔mainmust bestaticso it runs before any object is created.
🧠 Active Recall
Why must
mainbe declaredstatic, and what doesString[] argshold?Answer
- Short answer:
staticlets the JVM invokemainwithout first constructing an object of the class (there is none yet at start-up);argsholds the command-line arguments passed after the class name.- Why: Entry before instances ➔ a class-level (static) method belongs to the class, so it’s callable without
new.