Installing Java and First Program

Install the JDK

  1. Download a JDK 21 build: Oracle JDK, Eclipse Temurin (adoptium.net) or Amazon Corretto. All are free for learning.
  2. Run the installer (Windows .msi / macOS .pkg) or use a package manager: winget install EclipseAdoptium.Temurin.21.JDK, brew install openjdk@21, sudo apt install openjdk-21-jdk.
  3. Make sure JAVA_HOME points to the JDK folder and %JAVA_HOME%\bin (or $JAVA_HOME/bin) is on the PATH.
  4. Open a new terminal and check the version.

Verify

Check that Java is installed:

java -version
javac -version

Example output

openjdk version "21.0.4" 2024-07-16 LTS
OpenJDK Runtime Environment Temurin-21.0.4+7 (build 21.0.4+7-LTS)
OpenJDK 64-Bit Server VM Temurin-21.0.4+7 (build 21.0.4+7-LTS, mixed mode, sharing)
javac 21.0.4

Choose an Editor

ToolWhy use it
IntelliJ IDEA Communitybest Java IDE, free, smart auto-complete and refactoring
VS Code + Extension Pack for Javalightweight, good if you already use VS Code
Eclipseclassic free IDE, still common in companies
Careeroza code runner / jshelltry small snippets without any setup

Write, Compile and Run

Create a file named Main.java. The file name must match the public class name.

Example

Main.java

public class Main {
    public static void main(String[] args) {
        System.out.println("My first Java program!");
    }
}

Output

My first Java program!

From the Terminal

Compile with javac (creates Main.class), then run with java:

javac Main.java
java Main

Example output

My first Java program!

Tip: Since Java 11 you can skip the compile step for a single file: java Main.java compiles in memory and runs it.

Understanding Each Part

CodeMeaning
public class Maindeclares a class named Main; all code lives inside a class
public static void main(String[] args)the entry point; the JVM calls this method first
System.out.println(...)prints a line of text to the console
{ }curly braces mark the start and end of a block
;every statement ends with a semicolon

Exercise: Write a program that prints your name on the first line and your city on the second line.

Show answer
public class Main {
    public static void main(String[] args) {
        System.out.println("Ravi Kumar");
        System.out.println("Hyderabad");
    }
}