Explain Codes LogoExplain Codes Logo

Does the 'java' command compile Java programs?

java
bytecode
jit-compilation
runtime-optimizations
Alex KataevbyAlex Kataev·Feb 5, 2025
TLDR

No, the java command does not compile Java source files. Instead, use the javac command to compile your .java files into .class bytecode files. Then, execute the compiled code with java.

Compile with:

// The coding dojo begins here... javac MyClass.java

Run using:

// Time to witness the magic! java MyClass

So, javac is your mate for compilation, and java is your buddy for execution.

Streamlining execution in Java 11

From Java 11 onwards, the java command can also run single-source files directly, bypassing the explicit compilation step (javac). This feature hails from JEP 330 to enhance educational experiences and development of minor programs. Note that it won't generate .class files so for sharing or distribution, javac is still your go-to guy.

JEP 330: Simplifying Single-File Execution

With JEP 330, developers can now run single-source files without compilation. As long as you observe file-name consistency (public class name == file name), the java tool can directly execute it. It's a smooth integration, aligning with traditional Java usage and is designed to be friendlier to newbies.

Running your Java Code: An Inside View

When embellishing the intricacies of Java's code execution, we need to define the lines between bytecode interpretation and Just-In-Time (JIT) compilation. Modern Java runtimes use JIT compilation to optimize bytecode during execution and convert hot paths into efficient native instructions tailored for the running environment.

Bytecode: The Key to Platform Independence

Bytecode, encapsulated within .class files generated by javac, is like the machine code for the Java Virtual Machine (JVM). It is platform-independent, enabling the same bytecode to run on any JVM-compliant device.

Just-In-Time (JIT) Compilation: Speed is Key

Java's java command implicitly employs JIT compilation. Bytecode sections that are frequently executed are converted to machine language at runtime. This dynamic compilation into native machine code enables your Java applications to run faster the more you run them.

Runtime Optimizations: The Thoughtful JVM

Java runtimes often decide to interpret bytecode, rather than JIT compile it, if the code sections are not crucial for performance. This decision-making process is part of Java's runtime optimization strategy that strikes a balance between speed and resource usage.

Running without Prior Compilation

From Java 11 onwards, running java ClassName without prior javac might actually run previously compiled .class files or directly interpret single-source files, given they follow correct naming conventions.