← Exit to Module 1: Getting Started with Java lessons
Module progress · 0%Lesson · 20 min
Module 1: Getting Started with Java
Lesson focusCompilation vs. Interpretation: Running Your Code
Understand the two-stage process of executing a Java program: compiling source code into bytecode and then running the bytecode on the JVM, both from the command line and an IDE.
01 · 25 minJava Ecosystem Deep Dive: JDK, JRE, and JVM ArchitectureLocked02 · 15 minUnderstanding Java BytecodeLocked03 · 30 minSetting Up Your Professional Development Environment (IDE)Locked04 · 20 minYour First Java Program: A Line-by-Line WalkthroughLocked05 · 20 minCompilation vs. Interpretation: Running Your CodeLocked06 · 15 minTroubleshooting: Common First-Time ErrorsLocked
The Two-Stage Process: Java is a compiled language, but it has an interpretation step. This hybrid approach is what gives it both performance and portability.
- Stage 1: Compilation: You write your code in a
.javafile. You then use the Java compiler (javac) to transform this human-readable source code into platform-independent bytecode, which is saved in a.classfile.
- Stage 2: Execution (Interpretation): You then use the
javacommand, which starts the JVM. The JVM loads your.classfile, verifies the bytecode, and then interprets and executes it. The JIT compiler may also kick in at this stage to optimize performance.
Running from the Command Line:
- 1. Save your code: Save your program as
MyProgram.java.
- 2. Open a terminal: Navigate to the directory where you saved your file.
- 3. Compile: Type
javac MyProgram.java. If there are no errors, aMyProgram.classfile will be created in the same directory.
- 4. Run: Type
java MyProgram(note: do not add the.classextension). The JVM will find and execute themainmethod in your class.
Running from an IDE (IntelliJ):
- An IDE automates this entire process. When you click the green 'Run' button next to your
mainmethod, IntelliJ automatically invokes thejavaccompiler in the background. If compilation is successful, it then immediately invokes thejavacommand to run the resulting.classfile, displaying the output in the console window at the bottom of the screen.
Mini-Exercise: Create a new Java file from the command line using a simple text editor. Add a main method that prints a different message. Compile and run it using javac and java commands in your terminal.
// 1. Save as MyFirstProgram.java
public class MyFirstProgram {
public static void main(String[] args) {
System.out.println("I am compiling and running from the command line!");
}
}
// 2. From the terminal, in the same directory:
// > javac MyFirstProgram.java
// > java MyFirstProgramLesson quiz