Install Java (JDK)

Install a modern JDK (21 LTS), verify the install, and compile and run your first program from the command line.

Choosing a JDK

Java has several free, production-grade JDK distributions. For new projects, use a current LTS (Long-Term Support) release:

Version Status
Java 21 Current LTS — recommended for new projects
Java 17 Previous LTS — still widely used in production
Java 8 Legacy LTS — still common in older enterprise codebases

Popular free distributions: Eclipse Temurin, Amazon Corretto, Oracle OpenJDK. They're all built from the same OpenJDK source and are interchangeable for almost all purposes.

Installing on Windows

  1. Download the Temurin 21 .msi installer from the Adoptium project.
  2. Run the installer — make sure "Set JAVA_HOME variable" and "Add to PATH" are checked.
  3. Open a new terminal and verify:
Bash
java -version
javac -version

Installing on macOS

Using Homebrew:

Bash
brew install --cask temurin
java -version

Installing on Linux (Debian/Ubuntu)

Bash
sudo apt update
sudo apt install openjdk-21-jdk
java -version

Verifying the install

Both commands should print a matching version:

Bash
$ java -version
openjdk version "21.0.3" 2024-04-16 LTS

$ javac -version
javac 21.0.3

If javac is missing but java works, you likely installed a JRE instead of a full JDK — reinstall using the JDK package.

Your first program

Create a file named exactly Main.javathe file name must match the public class name:

Java
public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}

Compile and run it from the terminal:

Bash
javac Main.java   # produces Main.class (bytecode)
java Main         # runs it on the JVM — note: no ".class" extension
Plaintext
Hello, World!

Real projects almost never compile with raw javac — they use Maven or Gradle to manage dependencies, run tests and package the app. A minimal Maven project structure looks like:

Plaintext
my-app/
├── pom.xml
└── src/
    └── main/
        └── java/
            └── Main.java
Bash
mvn compile   # compiles the project
mvn package   # builds a runnable .jar

Common mistakes

  • Naming the file differently from the public class it contains (App.java with public class Main will not compile).
  • Running java Main.class instead of java Main — the java launcher takes the class name, not a file name.
  • Installing only a JRE and wondering why javac isn't found.

Interview questions

Q: What happens if the file name doesn't match the public class name? The compiler refuses to compile it with an error like class Main is public, should be declared in a file named Main.java.

Q: What's the difference between java Main and java Main.java? java Main runs the already-compiled Main.class bytecode. Modern JDKs (11+) also support java Main.java as a convenience that compiles and runs single-file source in one step, without producing a .class file on disk.