Since Java 6, you can compile and run a Java compilation unit defined as a String or a File using standard APIs in the SDK (a compilation unit is basically everything that goes inside a .java file - package, imports, classes/interfaces/enumerations), take a look at this example. You can't run an arbitrary Java snippet like the one in your question, though.

If at all possible, it'd be a better idea to embed a different scripting language that allows you to run snippets of code from a Java program - for example, JavaScript, Groovy, MVEL, BeanShell, etc.

Answer from Óscar López on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 71874858 › how-do-i-execute-java-code-inside-a-java-program
How do I execute java code INSIDE a java program? - Stack Overflow
... You could save the contents ... binary with Runtime.getRuntime().exec("javac " + [insert the name of your java file here]); and Runtime.getRuntime().exec("java " + [insert class name here]);. Though of course this wouldn't ...
🌐
Medium
medium.com › @AlexanderObregon › executing-java-code-from-the-command-line-d6a3c09bb565
Executing Java Code from the Command Line | Medium
March 9, 2025 - If you are writing code that needs ... Once a Java program has been compiled into a .class file, it can be executed using the java command....
🌐
GeeksforGeeks
geeksforgeeks.org › java › compilation-execution-java-program
Compilation and Execution of a Java Program - GeeksforGeeks
October 14, 2025 - The JVM (Java Virtual Machine) reads the .class file and interprets the bytecode. JVM converts bytecode to machine readable code i.e. "binary" (001001010) and then execute the program.
Top answer
1 of 14
10

You're trying to execute "C:/". You'll want to execute something like:

"javaw.exe d:\\somejavaprogram\\program.jar"

Notice the path separators.

I'm assuming this is for an ad-hoc project, rather than something large. However, for best practice running external programs from code:

  • Don't hardcode the executable location, unless you're certain it will never change
  • Look up directories like %windir% using System.getenv
  • Don't assume programs like javaw.exe are in the search path: check them first, or allow the user to specify a location
  • Make sure you're taking spaces into account: "cmd /c start " + myProg will not work if myProg is "my program.jar".
2 of 14
8

You can either launch another JVM (as described in detail in other answers). But that is not a solution i would prefer.

Reasons are:

  • calling a native program from java is "dirty" (and sometimes crashes your own VM)
  • you need to know the path to the external JVM (modern JVMs don't set JAVA_HOME anymore)
  • you have no control on the other program

Main reason to do it anyway is, that the other application has no control over your part of the program either. And more importantly there's no trouble with unresponsive system threads like the AWT-Thread if the other application doesn't know its threading 101.

But! You can achieve more control and similar behaviour by using an elementary plugin technique. I.e. just call "a known interface method" the other application has to implement. (in this case the "main" method).

Only it's not quite as easy as it sounds to pull this off.

  • you have to dynamically include required jars at runtime (or include them in the classpath for your application)
  • you have to put the plugin in a sandbox that prevents compromising critical classes to the other application

And this calls for a customized classloader. But be warned - there are some well hidden pitfalls in implementing that. On the other hand it's a great exercise.

So, take your pick: either quick and dirty or hard but rewarding.

🌐
Javatpoint
javatpoint.com › how-to-compile-and-run-java-program
How to Compile and Run Java Program - Javatpoint
How to Compile and Run Java Program - How to Compile and Run Java Program with oops, string, exceptions, multithreading, collections, jdbc, rmi, fundamentals, programs, swing, javafx, io streams, networking, sockets, classes, objects etc,
🌐
W3Schools
w3schools.com › java › java_getstarted.asp
Java Getting Started
This will compile your code. If there are no errors in the code, the command prompt will take you to the next line. Now, type "java Main" to run the file: ... Congratulations! You have written and executed your first Java program.
🌐
freeCodeCamp
freecodecamp.org › news › how-to-execute-and-run-java-code
How to Execute and Run Java Code from the Terminal
March 10, 2022 - You can go into the directory where ... it first. To compile a Java code/program, we get the class file. Then we need to execute/run the class file....
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › How-to-run-a-java-program
What are the different steps involved to execute a Java program?
Java program execution follows 5 major steps, which are as follows: The very first step is to use a simple editor or IDE to write the Java program. Save the written code with .java extension.
🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-run-java-program
How to Run Java Program? - GeeksforGeeks
July 23, 2025 - This will create a .class file in the same directory. Step 6: Run your Java program by typing "java [filename]" in the command prompt/terminal. The program will execute and produce the output.
🌐
OneCompiler
onecompiler.com › java
Java Online Compiler
int i = 10; if(i % 2 == 0) { System.out.println("i is even number"); } else { System.out.println("i is odd number"); } Switch is an alternative to If-Else-If ladder and to select one among many blocks of code. switch(<conditional-expression>) { case value1: // code break; // optional case value2: // code break; // optional ... default: //code to be executed when all the above cases are not matched; }
🌐
OnlineGDB
onlinegdb.com › online_java_compiler
Online Java Compiler - online editor
/****************************************************************************** Online Java Compiler. Code, Compile, Run and Debug java program online. Write your code in this editor and press "Run" button to execute it.
🌐
DigitalOcean
digitalocean.com › community › tutorials › compile-run-java-program-another-java-program
How to Compile and Run Java Program from another Java Program | DigitalOcean
August 4, 2022 - We can also get this property from System getProperty method System.getProperty("file.separator"). Above program can be changed like below for system independent code. String separator = File.separator; System.out.println("File Serapartor = "+separator); separator = System.getProperty("file.separator"); System.out.println("File Serapartor = "+separator); runProcess("javac -cp src src"+separator+"com"+separator+"journaldev"+separator+"files"+separator+"Test.java"); System.out.println("**********"); runProcess("java -cp src com"+separator+"journaldev"+separator+"files"+separator+"Test Hi Pankaj");
Top answer
1 of 3
2

tl;dr

In modern Java, as a convenience to beginner Java students, the java app will graciously compile, and then run, a .java file.

Think of it as java app detecting a source-code file, then sub-contracting the compilation work out to javac app, caching the compiled class in memory, and lastly continuing onwards to run the newly compiled class.

Details

A JDK comes bundled with a few dozen tools. A couple of these are crucial:

  • javac — Compiles .java file of source code text into .class file of bytecode.
  • java — Execute that .class file by launching a JVM.

The process steps are:

  1. You write Java source code in a .java file, including a main method inside a class definition.
  2. You submit that file to a compiler, such as the javac app bundled with every JDK.
  3. The compiler outputs a .class file.
  4. You execute (run) the main method by launching the java app bundled with every JDK.

You can skip some steps.

  • Compile and run a single file:
    As of Java 11, you can point the java app to a .java file. The java app will automatically compile first, as if javac were called on your behalf. Then the java app will go on to run the newly compiled class.
    • No .class file is written to storage. The compiled class is cached in memory.
    • See JEP 330: Launch Single-File Source-Code Programs for all the details.
    • This behavior is what you noted: However, java HelloWorld.java was executed properly without making HelloWorld.class.
  • Simplified main
    As a preview feature in Java 21, you can:
    • Write your java file without declaring a class. Just write the main method alone, with nothing around it.
    • Drop the public static from your main method declaration.
    • See JEP 445: Unnamed Classes and Instance Main Methods (Preview) for details.

Motivation

The Java team is making concerted efforts to ease the way for beginning Java programmers, to smooth over the initial speed bumps. They are trying to mask some of the elaborate ceremony, and make the tooling more friendly and accommodating.

The underlying structures and features of Java are still in place. This is not a “dumbing-down” of Java. These efforts are just attempts at making reasonable accommodations for beginners.

Hello World

Combining these features, getting started with a Hello World app is a simple as writing the following in a HelloWorld.java file:

void main() {
    System.out.println("Hello, World!");
}

… and then on the command-line calling:

java HelloWorld.java

Result on the console:

Hello, World!

That is a vast reduction in labor and confusion for a brand-new student of Java.


jshell

By the way… Another piece of making Java easier to use is jshell, a REPL for Java.

Both beginners and pros find jshell handy for running short bits of Java with immediate feedback.

BlueJ

Another useful tool for beginners is BlueJ, an IDE designed for students.

2 of 3
1

As mentioned in the JEP-330, for your example

java HelloWorld.java

is informally equivalent to

javac -d <memory> HelloWorld.java
java -cp <memory> hello.World
🌐
Medium
medium.com › @Mark.io › running-arbitrary-java-code-on-the-fly-d5003ebd46a8
Running Arbitrary Java Code On The Fly | by Murat Kilic | Medium
September 13, 2019 - As for executor code itself, after we skip the code for parsing command line options, we end up at this piece of code, where jarName and className are arguments to the program. This is where we locate the jar file and load the class and create an instance of it (to be used by invoke method later) ClassLoader classLoader = JavaExecutor.class.getClassLoader(); Path jarPath = Paths.get(jarName); URLClassLoader urlClassLoader = new URLClassLoader( new URL[] {jarPath.toUri().toURL()}, classLoader); Class executableClass = urlClassLoader.loadClass(className); Object obj1=executableClass.newInstance();
🌐
Princeton CS
introcs.cs.princeton.edu › java › 11hello
1.1 Your First Java Program: Hello World
June 10, 2022 - Compile it by typing "javac MyProgram.java" in the terminal window. Execute (or run) it by typing "java MyProgram" in the terminal window.