Launching single file source code programs

Imagine being able to execute a Java application without compilation; for instance, if you define the following Java class in HelloNoCompilation.java:

class HelloNoCompilation { 
    public static void main(String[] args) { 
        System.out.println("No compilation! Are you kidding me?"); 
    } 
} 

With Java 11, you can execute it using the following command (no compilation takes place):

    > java HelloNoCompilation.java

Note that the preceding command starts the JVM using java, which is passed the name of a source file with the .java extension. In this case, the class is compiled in memory before it is executed by the JVM. This applies to multiple classes or interfaces that are defined within the same source file. Here's another example (consider it to be defined within the same HelloNoCompilation.java source file):

class HelloNoCompilation { 
    public static void main(String[] args) { 
        System.out.println("No compilation! Are you kidding me?"); 
        EstablishedOrg org = new EstablishedOrg(); 
        org.invite(); 
        System.out.println(new Startup().name); 
    } 
} 
class Startup { 
    String name = "CoolAndExciting"; 
} 
interface Employs { 
    default void invite() { 
        System.out.println("Want to work with us?"); 
    } 
} 
class EstablishedOrg implements Employs { 
    String name = "OldButStable"; 
} 

On execution, you will see the following command:

    > java HelloNoCompilation.java

The preceding code will output as follows:

    No compilation! Are you kidding me?
    Want to work with us?
    CoolAndExciting  

With JEP 330, you can cut down the step of compiling your code and go to the execution of your Java applications straight away. However, this only applies to applications with a single source file. The source file can define multiple classes or interfaces, as shown in the preceding example code.

Launching single file source code programs helps to reduce the ceremony attached to simple code execution. This is the most helpful for students or professionals who are beginning to learn Java. However, when they move to working with multiple source files, they'll need to compile their code before executing them.

However, if you compile your source class using the javac command and then try to launch it as a single file source code, it won't execute. For example, compile the HelloNoCompilation source file, as follows:

    > javac HelloNoCompilation.java

Then, try to execute the following command:

    > java HelloNoCompilation.java  

You'll receive the following error:

    error: class found on application class path: HelloNoCompilation  
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.31.125