As anticipated in my last blog, I would like to start a series of posts to share some features of Java 11 I am learning while studying for the Oracle Certification (JavaSE-11 Programmer I).
This week we start with the one-line-source-code.
As you probably all know, the standard way to compile and run a Java application from a terminal is to execute the following commands:
javac MyClass.java java MyClass
where the first one invokes the compiler, specifying the name of your .java class with the extension. This translates your program into bytecode and produces the corresponding .class file that the JVM will execute. While, the second command launches the JVM, which is responsible for interpreting the .class file and actually run your application.
Nothing new so far, I bet. Well, the news is that, starting with Java 11, there is the possibility to combine these two commands in just one line, by simply typing:
Note that we used the
java command and not the
javac one, but we specified the .java extension, as we did at compile time in the first case. This command still compiles your code first, but it does not create any .class file, and then, if compilation succeeded, it launches the application.
That been said, keep in mind that it is still more efficient to compile and execute your application in two separated steps, so this is really a shortcut to use when you have to deal with a lot of small programs, but probably not at production time.
Furthermore, there are some restrictions to the use of this approach. It is called, as mentioned in the title, one-line-source-code. What does that mean? A one-line-source-code is a program which fits into a single source file, meaning that this approach can only be used when your executable class does not import any other class, except from the ones that come with the JDK or are in the same source file.
To conclude, just keep in mind that if you are testing some classes which do not require any particular import, you can use this more practical way to compile and execute your program in just one line!
This is all for the first episode. Stay tuned for the second post of the series, in which we will talk about another feature which was not with Java since the beginning, but it was introduced with Java 10: the var keyword!
by Ilenia Salvadori