Launch Single-File Source-Code Programs

Quick Summary:

  • Lets us run single-source-file programs directly via the java command, eliminating the need for explicit compilation, ideal for quick testing or scripting in Java.
  • Released in Java 11 (2018).

Example

Before Java 11:

Traditionally, running some Java source code involved multiple steps:

  1. Compile the code using command javac FooBar.java, producing a .class file containing the bytecode.
  2. Run the compiled class file using java FooBar.

After Java 11:

You can now run a single Java file directly without explicit compilation:

  1. Run the program directly from the command line (no compilation required)

👩‍💻 Hands-on Demo: Single-File Source-Code Programs

  1. Write a simple program in a single file that greets you by your name along with the current date.
  2. Run the program using a single command.

  3. Modify the program to check for the presence of arguments (the args parameter in the main-method), and if so greets all the given arguments with the current date, otherwise just uses “world” as a default.
  4. Run the program with your name and two other people’s names as the arguments to see the personalised greetings.




Solutions

🕵️‍♂️ Click here to reveal the solutions
public class SingleFileDemo {
    public static void main(String[] args) {
        if(args != null && args.length > 0) {
            for (String arg : args) {
                greet(arg);
            }
        } else {
            greet("world");
        }
    }

    private static void greet(String name) {
        LocalDate today = LocalDate.now();
        System.out.printf("Hello, %s! Today is %s %s!\n", name , today.getDayOfWeek(), today.format(DateTimeFormatter.ofPattern("d MMMM yyyy")));
    }
}

Summary

  • Simplified Execution: Java 11, released in 2018 and detailed in JEP 330, allows single-source-file programs to be run directly with the java command, eliminating the need for explicit compilation. This feature enhances the ease of testing and scripting.
  • Efficient Development Workflow: By enabling direct execution from the command line, Java 11 streamlines the development process, making it quicker and more accessible for beginners to test and run their Java code.