0% found this document useful (0 votes)
6 views5 pages

Execute Java Single-File Programs

Uploaded by

patrickmole
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views5 pages

Execute Java Single-File Programs

Uploaded by

patrickmole
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Launching Single-File Source-Code Programs

Single-File Source-Code Program Execution

In JDK 11, Java introduced the ability to launch a single-file source-code program with the java launcher,
without first needing to explicitly compile the source code. This works by the java launcher automatically
invoking the compiler and storing the compiled code in-memory. This can be a great way to learn how to
use Java or explore new features within the Java API, without having to go through the cruft of compiling
and then executing code. There are several ways to use this feature, as well as some limitations and
things to keep in mind.

Executing Your First Single-File Source-Code Program

To execute a single-file source-code program, the first class defined in the source file must contain public
static void main(String[]) like in HelloWorld below:

public class HelloWorld {

public static void main(String[] args) {

[Link]("Hello World!");

Copy

From the command line, HelloWorld can be launched with (accepting the name of the file is
also [Link]):

$ java [Link]

Copy

Passing in Arguments

Arguments can also be passed in like with a normally compiled class, so in the below:

public class HelloJava {

public static void main(String[] args) {

[Link]("Hello " + args[0]);


}

Copy

Passing in an argument can be done like this:

$ java [Link] World!

Copy

Multiple Classes in Same File

Multiple classes can be defined within the same source file if needed for encapsulation purposes, like in
this example:

public class MultipleClassesInSameFile {

public static void main(String[] args) {

[Link]([Link]());

[Link]([Link]());

class GenerateMessage {

static String generateMessage() {

return "Here is one message";

class AnotherMessage {

static String generateAnotherMessage() {

return "Here is another message";

}
}

Copy

When executed:

$ java [Link]

Copy

Will output:

Here is one message

Here is another message

Copy

Reference JDK Classes and Non-JDK Classes

A class that is part of the core JDK does not need to be added to the classpath to be executed. So this
example, referencing the Scanner and MatchResult classes, can be executed simply with
the java launcher:

import [Link];

import [Link];

public class ScannerExample {

public static void main(String... args) {

String wordsAndNumbers = """

Longing rusted furnace

daybreak 17 benign

9 homecoming 1

freight car

""";

try (Scanner scanner = new Scanner(wordsAndNumbers)) {

[Link]("benign").map(MatchResult::group).forEach([Link]::println);
}

Copy

To launch:

$ java [Link]

Copy

However the below example referencing RandomUtils, part of the Apache Commons Lang, will need to
have the [Link] added to the classpath at launch:

import [Link];

public class ReferenceNonJDKClass {

public static void main(String[] args) {

[Link]([Link]());

Copy

To launch:

java -cp /path/to/[Link] [Link]

Copy

Executing as a Shebang File

On a Unix-like operating system, a single-file source-code application, can also be launched as a shebang
file like a script. Within the a java source file, as the first line in the file add path/to/java/home --source
<version> like in the below example:

#!/path/to/your/bin/java --source 23

public class HelloJava {


public static void main(String[] args) {

[Link]("Hello " + args[0]);

Copy

The file cannot have .java as its file extension, and must also be executable chmod +x. With that, it can
be launched with:

./HelloJava

Common questions

Powered by AI

When executing programs with multiple classes within a single file using the Java launcher, all classes are compiled in-memory during execution. However, only the class with the public static void main method is the entry point. Encapsulation here ensures that supporting classes work exclusively within the scope of this main class, preventing them from being part of the broader accessible API. As such, encapsulation leverages in-file organization and structural clarity without necessitating multiple files .

In Java's single-file source-code execution, core JDK classes can be used directly without specifying a classpath, due to their inherent integration within the Java runtime. For example, classes such as Scanner can be directly utilized within such single-file programs. However, third-party library classes, like those from Apache Commons Lang, require their respective JAR files to be explicitly included in the classpath during execution. This difference emphasizes the self-contained nature of core JDK classes versus the dependency management necessary for third-party libraries .

The single-file execution feature in JDK 11 allows Java developers to explore new Java APIs interactively without setting up complex build environments or manually handling compilation. This contrasts with traditional methods that required developers to set up IDE projects or command line scripts for compiling and running each exploration step. Single-file execution significantly reduces setup time and encourages a more exploratory and iterative approach to learning APIs, allowing developers to experiment with API features on-the-fly through direct code input .

Java's single-file source-code execution feature allows developers to run Java programs without explicitly compiling them first by using the java launcher, which compiles the source code in-memory. This capability simplifies the learning process by removing the need for separate compilation steps, making it easier to quickly test and explore Java code and features interactively .

In JDK 11's single-file source-code feature, multiple classes can be defined within the same source file for encapsulation purposes. These additional classes can support the main class by encapsulating certain functionalities separately, although they are not public and can't be directly accessed from outside packages. This approach allows developers to manage related classes conveniently in one file without affecting module encapsulation negatively, offering localized encapsulation rather than modular .

To utilize external libraries like Apache Commons Lang in a single-file source-code approach, you must include the library's JAR file in the classpath during execution. For example, if using RandomUtils from Apache Commons Lang, the command should be: java -cp /path/to/commons-lang3-3.12.0.jar ReferenceNonJDKClass.java. This ensures that the classpath includes the necessary classes in the external library for execution, as single-file execution does not automatically resolve dependencies outside the JDK .

To execute a Java program using the single-file source-code execution feature with arguments, you first write the Java class with a main method. For instance, a class named HelloJava can be run from the command line with arguments using: $ java HelloJava.java World!. This differs from executing a pre-compiled Java program, where you would first compile the source into bytecode using javac and then execute the bytecode with java. Here, the command invokes the compilation in-memory and directly runs the program, allowing arguments to be passed just like with a compiled class .

To execute a Java file as a shebang script, you must add a shebang line to the first line of the file: #!/path/to/your/bin/java --source <version>. The file must not have a .java extension and should be made executable with chmod +x. Launching it is then done just like a script, e.g., ./HelloJava. This method provides a script-like execution experience but is limited by its reliance on Unix-like systems, inability to utilize classpath-based JARs without additional configuration, and requiring the Java executable path to be specified correctly .

The main benefit of using the Java shebang method is its simplification of running Java programs in script-like fashion, fostering rapid prototyping and easing the setup of lightweight Java applications in environments supporting scripts. However, its drawbacks include its dependency on Unix-like systems, requirement for executable permissions, and limitations in interacting with complex Java project structures that involve external dependencies. These constraints make it less versatile than regular Java execution methods for larger projects .

Java's single-file source-code program execution primarily limits usage to single-file applications, making it unsuitable for projects requiring complex configurations or multiple files. Libraries outside the JDK must be manually added to the classpath, limiting the seamless integration of third-party dependencies. Additionally, considerations regarding the platform-specific nature of shebang execution and the lack of persistent bytecode for debugging or distribution further limit its applicability to certain scenarios .

You might also like