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
- Download the Temurin 21
.msiinstaller from the Adoptium project. - Run the installer — make sure "Set JAVA_HOME variable" and "Add to PATH" are checked.
- Open a new terminal and verify:
java -version
javac -version
Installing on macOS
Using Homebrew:
brew install --cask temurin
java -version
Installing on Linux (Debian/Ubuntu)
sudo apt update
sudo apt install openjdk-21-jdk
java -version
Verifying the install
Both commands should print a matching version:
$ 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.java — the file name must match the public class name:
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Compile and run it from the terminal:
javac Main.java # produces Main.class (bytecode)
java Main # runs it on the JVM — note: no ".class" extension
Hello, World!
Using a build tool (recommended beyond "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:
my-app/
├── pom.xml
└── src/
└── main/
└── java/
└── Main.java
mvn compile # compiles the project
mvn package # builds a runnable .jar
Common mistakes
- Naming the file differently from the
public classit contains (App.javawithpublic class Mainwill not compile). - Running
java Main.classinstead ofjava Main— thejavalauncher takes the class name, not a file name. - Installing only a JRE and wondering why
javacisn'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.