DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Java
  4. Single File Source Code With Java 11

Single File Source Code With Java 11

Learn more about the newest addition in Java 11 — single file source code.

Uday Tatiraju user avatar by
Uday Tatiraju
·
May. 13, 19 · Presentation
Like (10)
Save
Tweet
Share
14.97K Views

Join the DZone community and get the full member experience.

Join For Free

One of the many salient features of Java 11 is the ability to directly run a single file of Java source code without the need to compile the source code first. Complementing JShell, this feature helps in learning Java and in writing simple utility applications and CLIs.

Say you created a HelloWorld.java file that, you guessed it, prints “Hello World”:

public class HelloWorld {
    public static void main (String... args) {
        System.out.println("Hello World");
    }
}


With JDK 11 installed, you can run this file using the “java” launcher:

java HelloWorld.java


The “java” launcher in JDK 11 has been updated to operate in four modes:

  • Launch a class file
  • Launch the main class of a jar
  • Launch the main class of a module
  • Launch the class declared in a single source file

The “java” launcher identifies the single file mode when one of the following two conditions match:

  • The first item passed to it is the class file with the “.java” extension
  • The “ — source” (read dash) option is specified

Shebang Support

As mentioned earlier, the single file mode can be useful to create small utility programs. The Shebang (“#!”) mechanism available on Unix-based systems is a perfect fit to run such single file utility programs. A shebang file to invoke the Java launcher using single file mode should begin with:

/path/to/java --source version


The shebang line can include other launcher options like adding additional classpath jars. Of course, the file should be marked as executable. Note that when you include the shebang line, your single file source code name need not follow the Java class naming conventions. For example, the HelloWorld.java can be renamed to “hello”.

Shebang support is not natively available in Windows

Equipped with this knowledge, let’s create a small program that runs Tomcat as an Embedded (TED) server. Download the embedded tomcat zip file and unzip the required jars into a “lib” folder. Next, create a file named “ted” and mark it as executable:

touch ted && \  
chmod +x ted


Add the following code to the file:

#!/usr/bin/java --class-path ./lib/* --source 11

import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

public class TomcatEmbedded {

    private static final String EMPTY = "";

    public static void main(String... args)
        throws Exception {
        File baseFolder = new File(System.getProperty("user.dir"));
        File appsFolder = new File(baseFolder, "apps");

        Tomcat tomcat = new Tomcat();
        tomcat.setBaseDir(baseFolder.getAbsolutePath());
        tomcat.setPort(8080);
        tomcat.getHost().setAppBase(appsFolder.getAbsolutePath());

        // Call the connector to create the default connector.
        tomcat.getConnector();

        tomcat.addWebapp(EMPTY, ".");
        Wrapper wrapper = tomcat.addServlet(EMPTY, "hello", new HelloServlet());
        wrapper.setLoadOnStartup(1);
        wrapper.addMapping("/*");

        tomcat.start();
        tomcat.getServer().await();
    }

    private static class HelloServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
            resp.setStatus(200);
            var writer = resp.getWriter();
            writer.write("Hello World");
            writer.flush();
            writer.close();
        }
    }
}


Save the file and run the file as a regular executable:

./ted


Navigate to http://localhost:8080 in your browser to see the utility program in action. Granted, “ted” isn’t useful in its current incarnation but one can extend it to build a small developer “Dropbox” utility program to share files across VMs.

The possibilities to create self-contained utility programs in Java are endless with this new single file source code feature.

Happy Coding!

Java (programming language)

Published at DZone with permission of Uday Tatiraju, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Monolithic First
  • What Are the Benefits of Java Module With Example
  • Introduction to Spring Cloud Kubernetes
  • DevOps for Developers: Continuous Integration, GitHub Actions, and Sonar Cloud

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: