← Back to Index

Chapter 1: Environment Setup

Install JDK 21, configure development environment

1. Installing JDK 21

Java 21 is the latest Long-Term Support (LTS) version, recommended for production use. Choose the installation method for your platform.

macOS (Homebrew)

On macOS, Homebrew is recommended to install Temurin (an open-source JDK distribution maintained by Eclipse):

# Install JDK 21 (Temurin distribution)
brew install --cask temurin@21

# Or use SDKMAN (recommended for managing multiple JDK versions)
curl -s "https://get.sdkman.io" | bash
sdk install java 21.0.4-tem

# Verify version
java --version

Tip: SDKMAN is a widely used version manager in the Java ecosystem, similar to nvm for Node.js. It makes switching between different JDK versions effortless.

Ubuntu / Debian

# Install OpenJDK 21
sudo apt update
sudo apt install openjdk-21-jdk

# If not available in repos, use Adoptium (Temurin)
sudo apt install -y wget apt-transport-https
wget -qO - https://packages.adoptium.net/artifactory/api/gpg/key/public | sudo tee /etc/apt/trusted.gpg.d/adoptium.asc
echo "deb https://packages.adoptium.net/artifactory/deb $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/adoptium.list
sudo apt update
sudo apt install temurin-21-jdk

# Verify version
java --version

Windows

# Option 1: Using Scoop (recommended)
scoop bucket add java
scoop install temurin21-jdk

# Option 2: Using Chocolatey
choco install temurin21

# Option 3: Manual download
# Download JDK 21 installer from https://adoptium.net/
# After installation, add JAVA_HOME and bin directory to PATH

Verify Installation

$ java --version
openjdk 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)

$ javac --version
javac 21.0.4

πŸ”„ Comparison with Other Languages

Python uses python3 --version, Node.js uses node -v, PHP uses php -v. Java's version check command is java --version β€” note the double dash.

2. JAVA_HOME & Environment Variables

Many Java tools (Maven, Gradle, IDEs) depend on the JAVA_HOME environment variable. Make sure it points to the correct JDK installation path.

# macOS / Linux - Check JAVA_HOME
echo $JAVA_HOME

# If empty, set manually (add to ~/.zshrc or ~/.bashrc)
export JAVA_HOME=$(/usr/libexec/java_home -v 21)  # macOS
export JAVA_HOME=/usr/lib/jvm/temurin-21-jdk-amd64  # Ubuntu
export PATH=$JAVA_HOME/bin:$PATH

# Windows (PowerShell)
echo $env:JAVA_HOME
# Add JAVA_HOME via System Settings > Environment Variables

Note: If you use SDKMAN to manage JDK versions, it automatically sets JAVA_HOME β€” no manual configuration needed.

3. Hello World

Let's write a Java program to understand the basic structure. Java 21 supports running single-file programs directly without manual compilation.

// Hello.java
public class Hello {
    public static void main(String[] args) {
        String name = "Java";
        int version = 21;
        String[] features = {"Record", "Sealed Class", "Pattern Matching", "Virtual Threads"};

        System.out.println("Hello, " + name + " " + version + "!");

        // Text Block - Java 13+
        String message = """
                Java %d new features:
                """.formatted(version);
        System.out.print(message);

        // Enhanced for loop
        for (int i = 0; i < features.length; i++) {
            System.out.println("  " + (i + 1) + ". " + features[i]);
        }

        System.out.println(greet("Java 21"));
    }

    static String greet(String who) {
        return "Welcome to " + who + "!";
    }
}

Save and run:

# Method 1: Traditional compile and run
$ javac Hello.java
$ java Hello

# Method 2: Direct run (Java 11+, single-file no compile needed)
$ java Hello.java

Hello, Java 21!
Java 21 new features:
  1. Record
  2. Sealed Class
  3. Pattern Matching
  4. Virtual Threads
Welcome to Java 21!

Quick Syntax Reference:

  • β€’ Filename must match the public class name
  • β€’ Entry method signature is fixed: public static void main(String[] args)
  • β€’ Every statement ends with ;
  • β€’ String concatenation uses +
  • β€’ Java is strongly typed β€” variables must have declared types (or use var for inference)

πŸ”„ Execution Method Comparison

Java java Hello.java (single-file) or javac + java
Python python hello.py
TypeScript npx tsx hello.ts
Go go run hello.go

Java 11+ supports single-file direct execution (java File.java), no explicit compilation needed, closer to scripting language experience.

4. Installing Maven

Maven is the most popular build and dependency management tool for Java, equivalent to npm for Node.js, pip for Python, and Composer for PHP.

Installing Maven

# macOS
brew install maven

# Ubuntu / Debian
sudo apt install maven

# Windows (Scoop)
scoop install maven

# Or via SDKMAN
sdk install maven

# Verify installation
mvn --version

Initialize a Project

# Create project skeleton using Maven archetype
mvn archetype:generate \
  -DgroupId=com.example \
  -DartifactId=my-java-project \
  -DarchetypeArtifactId=maven-archetype-quickstart \
  -DarchetypeVersion=1.5 \
  -DinteractiveMode=false

cd my-java-project

Generated project structure:

my-java-project/
β”œβ”€β”€ pom.xml                  # Maven config file (like package.json)
└── src/
    β”œβ”€β”€ main/java/com/example/
    β”‚   └── App.java          # Main program
    └── test/java/com/example/
        └── AppTest.java      # Tests

pom.xml is the project's core configuration file:

<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>my-java-project</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!-- Example dependency: Gson JSON library -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.11.0</version>
        </dependency>
    </dependencies>
</project>

Common Maven Commands

# Compile project
mvn compile

# Run tests
mvn test

# Package as JAR
mvn package

# Clean build artifacts
mvn clean

# Install to local repository
mvn install

πŸ”„ Package Manager Comparison

Language Tool Config File Repository
Java Maven pom.xml Maven Central
Node.js npm package.json npmjs.com
Python pip requirements.txt PyPI
PHP Composer composer.json Packagist

5. IDE Configuration

For Java development, IntelliJ IDEA is the recommended IDE. The Community Edition is free and fully featured for Java development.

🧠

IntelliJ IDEA

The most popular Java IDE β€” intelligent completion, refactoring, and debugging all-in-one. Community Edition is free.

jetbrains.com/idea
πŸ’»

VS Code + Java Pack

Lightweight option β€” install Extension Pack for Java for full Java development support.

vscjava.vscode-java-pack
🌐

Eclipse

A veteran open-source IDE, still widely used in enterprise environments with a rich plugin ecosystem.

eclipse.org

If using VS Code, install the Extension Pack for Java:

# VS Code command line install
code --install-extension vscjava.vscode-java-pack

Recommended: If you're new to Java, IntelliJ IDEA Community Edition is strongly recommended. Its intelligent suggestions and refactoring capabilities far exceed other editors, significantly boosting your learning efficiency. Install via brew install --cask intellij-idea-ce (macOS).

6. JShell Interactive Programming

Java 9 introduced JShell (REPL), allowing you to quickly test code snippets like Python's interactive interpreter.

$ jshell
|  Welcome to JShell -- Version 21.0.4
|  For an introduction type: /help intro

jshell> var name = "Java 21"
name ==> "Java 21"

jshell> System.out.println("Hello, " + name)
Hello, Java 21

jshell> List.of(1, 2, 3).stream().map(x -> x * x).toList()
$3 ==> [1, 4, 9]

jshell> record Point(int x, int y) {}
|  created record Point

jshell> new Point(3, 4)
$5 ==> Point[x=3, y=4]

jshell> /exit

πŸ”„ REPL Comparison

Java jshell β€” built-in since Java 9
Python python3 β€” enters interactive mode directly
Node.js node β€” enters REPL directly

JShell supports tab completion, multi-line code input, and auto-importing common classes β€” perfect for quickly validating ideas.

7. Chapter Summary

πŸ› οΈ Installing JDK

macOS: brew install --cask temurin@21, Ubuntu: apt install openjdk-21-jdk, or use SDKMAN for unified management. Verify with java --version.

βš™οΈ Environment Variables

Ensure JAVA_HOME points to the correct JDK path β€” many tools depend on it. SDKMAN users get this configured automatically.

πŸ“ Hello World

Java 11+ supports java File.java for direct single-file execution. Filename must match the public class name, entry point is main.

πŸ“¦ Maven

Java's package management and build tool. pom.xml is the config file, mvn compile compiles, mvn package creates a JAR.

πŸ’» IDE Selection

IntelliJ IDEA is the top choice, VS Code + Java Pack is a lightweight alternative. Using IDE intelligent suggestions is highly recommended.

πŸ–₯️ JShell

Java's built-in interactive programming environment, great for quickly testing code snippets with auto-completion and multi-line input support.