Java Learner logo
← Exit to Module 1: Getting Started with Java lessons
Module progress · 0%Lesson · 20 min

Module 1: Getting Started with Java

Lesson focus

Compilation 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.

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 .java file. You then use the Java compiler (javac) to transform this human-readable source code into platform-independent bytecode, which is saved in a .class file.
  • Stage 2: Execution (Interpretation): You then use the java command, which starts the JVM. The JVM loads your .class file, 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, a MyProgram.class file will be created in the same directory.
  • 4. Run: Type java MyProgram (note: do not add the .class extension). The JVM will find and execute the main method in your class.

Running from an IDE (IntelliJ):

  • An IDE automates this entire process. When you click the green 'Run' button next to your main method, IntelliJ automatically invokes the javac compiler in the background. If compilation is successful, it then immediately invokes the java command to run the resulting .class file, 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 MyFirstProgram

Lesson quiz

When running a compiled Java class named `Test` from the command line, which command is correct?

Next lesson →