Quiz: Compact Source Files and Instance Main Methods in Java 25
Study the lesson first: Compact Source Files and Instance Main Methods in Java 25
Total: 6 questions
1. What is a compact source file in Java, and since which version can you use it?
What is a compact source file in Java, and since which version can you use it?
A compact source file is a .java file whose methods and fields are written without a class declaration. When the compiler finds a method or a field at the top level, it wraps them in an implicitly declared class itself. The smallest program: void main() { IO.println("Hello, World!"); }.
The feature became standard in Java 25 (JEP 512). Before that there were four previews: Java 21 (JEP 445, "unnamed classes"), 22 (JEP 463, renamed to "implicitly declared classes"), 23 (JEP 477, class java.io.IO with statically imported methods and the automatic java.base import), 24 (JEP 495). Java 21–24 required the --enable-preview flag; from Java 25 on, no flags are needed.
You run such a file like any other: java Hello.java straight from the source, or javac Hello.java + java Hello. In the second case an ordinary Hello.class is produced. The classic public static void main(String[] args) keeps working.
2. What are the properties of an implicitly declared class in Java 25?
What are the properties of an implicitly declared class in Java 25?
The fields, methods and nested types of a compact file become members of the implicit class, so methods see the fields and each other, and this is available in instance methods. Properties of the class:
- its name comes from the file name:
Greeter.java→ classGreeter; - the class is
finaland cannot be extended; - it lives in the unnamed package; a
packagedeclaration is a compile error; - it cannot be referenced by name: even in the same file
new Greeter()givescannot find symbol; - it has only the default constructor; you cannot declare your own;
- it extends
Object; there is nowhere to writeextendsorimplements; - it must have a launchable
main, otherwisecompact source file does not have main method in the form of void main() or void main(String[] args).
Code outside methods is not allowed: a top-level IO.println("x"); does not compile. A nested class Helper in the file Helper.java is an inner class of the implicit class, its full name is Helper$Helper, and it can be created only from an instance method.
3. Which classes are available in a compact source file without an import?
Which classes are available in a compact source file without an import?
A compact source file behaves as if it started with import module java.base;. Without a single import, all public classes and interfaces of the packages exported by the java.base module are available: java.util, java.io, java.nio.file, java.math, java.time, java.util.function, java.util.stream, java.util.concurrent and others. So List, Map or Path work right away.
- Only
java.base:java.sql.Connectionorjavax.swing.JFramemust be imported explicitly.Datein a compact file meansjava.util.Date, with no clash withjava.sql.Date. - Explicit imports are allowed: regular
importandimport staticdeclarations go at the top of the file, as in any other. - The rule applies to compact files only: in a normal class only
java.langis imported automatically. So when you turn a compact file into a normal class (wrap the contents inclass Greeter { ... }), you must add explicit imports for everything that used to come fromjava.base; themainmethod does not have to change.
4. What is the java.lang.IO class, and how does IO.println() differ from System.out.println()?
What is the java.lang.IO class, and how does IO.println() differ from System.out.println()?
java.lang.IO is a final Java 25 class with static methods for console input and output: print(Object), println(Object), println(), readln() (reads a line, returns null at end of input) and readln(String prompt) (prints a prompt, then reads a line). It lives in java.lang, so it is available in any file, not only in compact ones.
The IO methods are not statically imported: you must write IO.println("x"), and a bare println("x") does not compile (cannot find symbol). Calling them without the prefix worked only in the Java 23–24 previews, where the class was java.io.IO.
The result of IO.println() is the same as System.out.println(): IO works on top of System.out and System.in, so System.setOut() redirects it too. The difference is convenience: the name is shorter, and IO.readln("Name: ") reads a line without a Scanner. IO has no printf and no readInt: you get a number with Integer.parseInt(), and formatting and System.err still need the standard streams.
5. Which forms of the main method are allowed in Java 25, and how does the JVM choose which one to run?
Which forms of the main method are allowed in Java 25, and how does the JVM choose which one to run?
JEP 512 changed the launch protocol: the JVM accepts four forms, public static void main(String[] args), static void main(), void main(String[] args) and void main(), and in any class, not only an implicit one. The return type is void; any access except private works.
Selection order:
- First the launcher looks for
main(String[] args), static or instance. - If there is none, it looks for
main()with no parameters. - A static method is called directly; for an instance method the JVM creates an object through a non-private no-argument constructor.
So with static void main() and void main(String[] args) in one class, main(String[]) runs: the parameter decides, not static. A static and an instance main with the same parameters cannot coexist: method main(String[]) is already defined. An inherited main also qualifies: if Inherit extends Base has no method of its own, the JVM calls Base.main() on an Inherit object.
6. Why can a program with an instance main fail to launch even though it compiles?
Why can a program with an instance main fail to launch even though it compiles?
To call an instance main method, the java launcher first creates an object of the class through a non-private no-argument constructor. The compiler does not check this, so the errors appear only at launch:
- only a
privateconstructor (or only constructors with parameters):Error: no non-private zero argument constructor found in class PrivCtor; - an
abstractclass:Error: abstract class Abstract can not be instantiated; - a
private void main()method is invisible to the launcher:Main method not found.
Fix: add a non-private no-argument constructor, make main static, or remove private from it.