The class and the entry point

Why a program is a class and not a free-standing script.

Java has no free-standing script that "just runs from top to bottom". The unit of a program is a class. A class describes data and methods. For the JVM to start at all, it needs a public class with the method public static void main(String[] args). The file name must match the name of the public class: the class Main lives in Main.java.

The main method is static because there is no object yet: the virtual machine does not know which instance to create. String[] args holds the command-line arguments. In the exercises the array is often empty, but you must not change the method signature. System.out.println writes a line and a line break. The check compares text with leading and trailing spaces trimmed.

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Tropa");
    }
}

A common mistake is naming the file hello.java while the class is Main, or forgetting static. Then java Main cannot find the entry point. The second mistake is printing extra text next to the expected phrase. A trailing space after println usually does no harm; an extra word already breaks the comparison.

Keep three things in mind: one public class per file, the file named after the class, and main as the only way in. Everything else is methods that main calls. A service will later grow into packages, but the entry point stays just as narrow.

Practice

  1. Why main

    Why does the first program have a main method rather than just a set of fields?

    • So that the class can be serialized
    • It is the entry point, and no object exists yet
    • So that the file is called Main.java
    • To import java.lang
  2. The file name

    The public class is called Main. What must the file be called?

  3. Your first program

    Finish the program so that it prints exactly Hello, Tropa and exits.