Join Kathryn Hodge for an in-depth discussion in this video Launch single-file source-code programs, part of First Look: Java 10 and Java 11.
- [Instructor] In Java 11, we'll also be able to launch single-file source code programs. This allows us to execute our Java source code directly using the Java interpreter. In Java 10, the Java Launcher operated in three modes. Launching a class file, launching the main class of a JAR file, and launching the main class of a module. Java 11 adds a fourth mode. Launching a class declared in a source file. How does this work? Well, the source code is compiled in memory and then executed by the interpreter.
Let's try an example. Now I'm in my code editor, I have this Hello.java file saved on my desktop, and we're going to write some Java code here. The first thing we're going to write is public class hello world so your basic Java boilerplate code. And then of course your main function here. So static void main string array arguments. Then to keep this simple, we are just going to print out hello and then whatever the user puts in.
So if we want to say hello Katherine, hello whatever name you want to say, or hello something else, that is what we're going to do right here. So to do this we'll write system.out.println string.format, and we'll just go hello % S and then put in the arguments at zero there, which will be our user's name. We'll save this up and then jump over to our terminal to run this code.
In my terminal, I'm going to write LS. And we can see the Hello.Java file is here on the desktop. To run this, this is where the new feature comes in. We are going to write Java hello.Java. And then whatever we want the name to be, whatever we want to print out. Hello blank, in this case, I'm going to put my name, Katherine. And there we see it, Hello Katherine. This is something that you could not do before Java 11. Before you had to compile your Java file into a class file and then run that code.
Now we can directly use the Java interpreter and run it from this Hello.Java file. So what's the limitation? Your program must be a single file program, where all of the code fits in a single source file. This means that all of your classes must be defined in the same file. This feature, along with the JShell is great for a beginner who just wants to try building simple programs. It's also great when you just need to write a simple utility program, or want to try out a new API.
- Local variable type inferences
- Garbage collection improvements
- Application class-data sharing
- Thread-local handshakes
- Standardizing the HTTP client
- JVM improvements