Sub topic 1
Java Compact Source Files and Instance Main Methods
Prerequisites
You should know basic Java syntax, including variables, methods, and control flow. You should also know what classes, fields, and methods are, and be familiar with compiling and running a traditional Java program.
Why Hello World needs so much ceremony
A traditional Java program looks like this:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, world!");
}
}Only one line produces output. The remaining parts satisfy Java's traditional launch rules:
public class Hellogives the program a named class.publicmakes the class and method accessible to the launcher.staticlets Java callmainwithout creating an object.voidsays the method returns no value.String[] argsreceives command-line arguments.System.out.printlnaccesses the console through a library class.
This structure is useful for larger programs, but it hides a simple first-program idea behind several concepts.
How the launcher chooses a main method
The Java launcher searches the selected class for a valid main method. Traditional programs use public static void main(String[] args). Newer Java versions also recognize parameterless forms and instance methods.
When several valid methods exist, the launcher prefers the static forms before instance forms, and parameterized forms before parameterless forms. The exact declaration still matters: a method with the wrong name, return type, or parameter type is not a launch method.
Instance main methods
An instance method belongs to an object rather than to the class itself. Java can create that object and then invoke its main method:
class Greeter {
private int count;
void main() {
count++;
IO.println("Greeting number " + count);
}
}Here, Java uses the accessible no-argument constructor, creates a Greeter, and calls main. The field can therefore hold state between calls on that object.
> callout note Instance main methods reduce ceremony, but the class must still be launchable and constructible. A constructor requiring arguments gives the launcher no way to create the instance automatically.
Compact source files
A compact source file omits the surrounding class declaration:
void main() {
IO.println("Hello, world!");
}The compiler treats the file as the body of an implicitly declared class. Top-level methods and fields become members of that class. This keeps small programs focused on their behavior while preserving Java's class-based model.
Exercise
What does Java create before calling the main method in the Greeter example?
Show answer
It creates a Greeter instance with its accessible no-argument constructor, then invokes the instance main method.