Skip to main content

Ch 1.2 Setting Up the Java Development Environment

To start Java development, you primarily need two things: the JDK to translate code into machine instructions, and an IDE to help you write code efficiently. This chapter walks you through every step from installing JDK 21 to running your first program.


1. What is the JDK?

The JDK (Java Development Kit) is a collection of tools required to develop and run Java programs.

ToolRole
javacCompiles source code (.java) into bytecode (.class)
javaLaunches the JVM and executes .class files
javadocGenerates HTML documentation from source code comments
jarPackages multiple .class files into a single .jar archive
jdbJava debugger

Choosing a JDK Distribution

Java has commercial versions (Oracle JDK) and free open-source versions (OpenJDK). For learning and personal projects, free OpenJDK-based distributions are recommended.

DistributionProviderNotes
OpenJDKOracleOfficial open-source reference implementation
Amazon CorrettoAmazonAWS-optimized, free long-term support
Eclipse TemurinEclipse FoundationAdoptium project, most widely used
Azul ZuluAzulBroad platform support
GraalVMOracleSupports native image compilation
tip

For learning purposes, Eclipse Temurin 21 LTS or Amazon Corretto 21 LTS are recommended. Both are free and provide guaranteed long-term support.


2. Installing JDK 21

2.1 Windows Installation

Option 1: Official Installer (Recommended)

  1. Visit the Eclipse Temurin Download page
  2. Select Java 21 (LTS) and download Windows x64 .msi
  3. Run the downloaded .msi file
  4. During installation, verify that "Set JAVA_HOME variable" and "Add to PATH" are checked
  5. Restart the Command Prompt after installation completes

Option 2: winget (Windows Package Manager)

# Run in PowerShell or cmd
winget install EclipseAdoptium.Temurin.21.JDK

Verify Installation:

java -version
javac -version

Expected Output:

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

2.2 macOS Installation

Option 1: Homebrew (Recommended)

# Install Homebrew if not already installed
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Temurin JDK 21
brew install --cask temurin@21

# Verify installation
java -version
javac -version

Option 2: Official Installer

  1. Visit the Eclipse Temurin Download page
  2. Select Java 21 (LTS) and choose macOS aarch64 (M1/M2/M3) or x64 (Intel)
  3. Download and run the .pkg file
  4. Follow the on-screen instructions to complete installation

Managing Multiple Versions with SDKMAN:

# Install SDKMAN
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"

# Install Java 21
sdk install java 21.0.2-tem

# List installed versions
sdk list java

# Switch versions
sdk use java 21.0.2-tem

2.3 Linux (Ubuntu/Debian) Installation

# Update package list
sudo apt update

# Add Temurin repository
wget -O - https://packages.adoptium.net/artifactory/api/gpg/key/public | \
sudo tee /etc/apt/keyrings/adoptium.asc

echo "deb [signed-by=/etc/apt/keyrings/adoptium.asc] \
https://packages.adoptium.net/artifactory/deb \
$(awk -F= '/^VERSION_CODENAME/{print$2}' /etc/os-release) main" | \
sudo tee /etc/apt/sources.list.d/adoptium.list

sudo apt update

# Install JDK 21
sudo apt install temurin-21-jdk

# Verify installation
java -version
javac -version

Switching between multiple JDK versions:

sudo update-alternatives --config java

3. Setting JAVA_HOME Environment Variable

JAVA_HOME is an environment variable that points to the JDK installation directory. Many tools like Maven and Gradle depend on this variable.

3.1 Windows

GUI Method:

  1. Press Windows key + R, type sysdm.cpl, press Enter
  2. Go to the Advanced tab and click Environment Variables
  3. Under System variables, click New
    • Variable name: JAVA_HOME
    • Variable value: C:\Program Files\Eclipse Adoptium\jdk-21.0.2.13-hotspot (confirm the actual installation path on your system)
  4. Find Path under System variables → EditNew
    • Add: %JAVA_HOME%\bin
  5. Click OK on all dialogs, then restart cmd

PowerShell Method (requires Administrator):

# Set JAVA_HOME
[System.Environment]::SetEnvironmentVariable(
"JAVA_HOME",
"C:\Program Files\Eclipse Adoptium\jdk-21.0.2.13-hotspot",
"Machine"
)

# Add to PATH
$currentPath = [System.Environment]::GetEnvironmentVariable("Path", "Machine")
[System.Environment]::SetEnvironmentVariable(
"Path",
"$currentPath;%JAVA_HOME%\bin",
"Machine"
)

Verify:

echo %JAVA_HOME%
# C:\Program Files\Eclipse Adoptium\jdk-21.0.2.13-hotspot

java -version

3.2 macOS

# Find JDK installation path
/usr/libexec/java_home -v 21

# Add to ~/.zshrc or ~/.bash_profile
echo 'export JAVA_HOME=$(/usr/libexec/java_home -v 21)' >> ~/.zshrc
echo 'export PATH=$JAVA_HOME/bin:$PATH' >> ~/.zshrc

# Apply changes
source ~/.zshrc

# Verify
echo $JAVA_HOME
java -version

3.3 Linux

# Find JDK installation path
which java
readlink -f $(which java)
# e.g., /usr/lib/jvm/temurin-21-amd64/bin/java

# Add to ~/.bashrc or ~/.profile
echo 'export JAVA_HOME=/usr/lib/jvm/temurin-21-amd64' >> ~/.bashrc
echo 'export PATH=$JAVA_HOME/bin:$PATH' >> ~/.bashrc

# Apply changes
source ~/.bashrc

# Verify
echo $JAVA_HOME
java -version

4. Installing and Configuring an IDE

IntelliJ IDEA is the most popular IDE for modern Java development.

EditionPriceKey Features
CommunityFreeJava, Kotlin, general development
UltimatePaidWeb frameworks, DB, Spring-specific features
tip

The Community edition is fully sufficient for learning. If you have a student email, you can get the Ultimate edition free with a JetBrains Student License.

Installation Steps:

  1. Visit JetBrains Downloads
  2. Download the Community installer for your OS
  3. Run the installer and proceed with the default options

Creating Your First Project:

  1. Open IntelliJ IDEA and click New Project
  2. Select Java
  3. Under JDK, select the installed JDK 21 (or click Download JDK if not listed)
  4. Enter project name: HelloJava
  5. Choose a save location and click Create
  6. Right-click the src folder → NewJava Class
  7. Enter class name: HelloWorld
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, IntelliJ IDEA!");
}
}
  1. Click the green triangle (▶) on the left side of the editor, or press Shift + F10 to run

Essential IntelliJ Shortcuts:

ShortcutAction
psvm + TabAuto-complete public static void main(String[] args)
sout + TabAuto-complete System.out.println()
Shift + F10Run the program
Shift + F9Run in debug mode
Ctrl + SpaceTrigger code completion
Alt + EnterShow quick fix suggestions
Ctrl + /Toggle line comment
Ctrl + Shift + FSearch everywhere

4.2 VS Code + Extension Pack for Java

VS Code, with the right extensions, can serve as a capable Java IDE.

Setup Steps:

  1. Download and install VS Code
  2. Open VS Code, go to Extensions(Ctrl + Shift + X)
  3. Search for "Extension Pack for Java" and install it (This pack includes Language Support for Java, Debugger for Java, Maven for Java, and more)
  4. Open the Command Palette (Ctrl + Shift + P) → type Java: Create Java Project
  5. Select No build tools(recommended for beginners)
  6. Choose a save location and enter a project name

Recommended settings.json:

{
"java.home": "C:/Program Files/Eclipse Adoptium/jdk-21.0.2.13-hotspot",
"editor.formatOnSave": true,
"editor.tabSize": 4,
"files.autoSave": "onFocusChange"
}

5. Your First Program: Hello World

Let's write, compile, and run a Java program from the terminal — without an IDE. Understanding this process makes the Java execution model clear.

5.1 Write the Source File

Create a file named Hello.java in any directory.

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

The filename must match the class name exactly. If the class is named Hello, the file must be named Hello.java. This is case-sensitive.

5.2 Compile

Navigate to the directory containing the file in your terminal, then compile.

# Move to the directory where the file is saved
cd C:\Users\YourName\Desktop\java_practice

# Compile (Hello.java → Hello.class)
javac Hello.java

# Confirm Hello.class was created
dir # Windows
ls -la # macOS/Linux

If compilation succeeds, no error messages appear and Hello.class is created.

5.3 Run

# Use the class name only — no file extension
java Hello

Output:

Hello, World!
Java programming starts here!
note

The java command takes the class name(Hello), not the filename (Hello.java). Do not include the .class extension.


6. Package Declarations and Directory Structure

Java packages are namespaces for organizing classes. The package name must exactly match the directory structure.

src/
└── com/
└── example/
└── myapp/
├── Main.java
└── util/
└── Helper.java
// File location: src/com/example/myapp/Main.java
package com.example.myapp; // Package declaration (at the very top)

import com.example.myapp.util.Helper; // Import another class

public class Main {
public static void main(String[] args) {
System.out.println("Package structure example");
Helper.sayHello();
}
}

Compiling and running files with packages:

# Run from the src directory
javac com/example/myapp/Main.java com/example/myapp/util/Helper.java

# Run using the fully-qualified class name
java com.example.myapp.Main

7. Build Tools Preview (Maven and Gradle)

In real-world projects, developers use build tools instead of running javac manually.

Maven

An XML-based build tool. Dependencies and build configuration are managed via pom.xml.

<!-- Basic pom.xml structure -->
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>my-app</artifactId>
<version>1.0.0</version>

<properties>
<java.version>21</java.version>
</properties>

<dependencies>
<!-- External library dependencies go here -->
</dependencies>
</project>

Gradle

A modern build tool using Groovy or Kotlin DSL.

// build.gradle (Groovy DSL)
plugins {
id 'java'
}

java {
sourceCompatibility = JavaVersion.VERSION_21
targetCompatibility = JavaVersion.VERSION_21
}

dependencies {
// External library dependencies go here
}

Comparing Build Tools:

FeatureMavenGradle
ConfigurationXML (pom.xml)Groovy/Kotlin (build.gradle)
PerformanceModerateFast (incremental build, caching)
Learning CurveLowModerate
Common Use CasesSpring legacy, enterpriseAndroid, new Spring Boot projects

8. Common Installation Errors and Solutions

Error 1: 'java' is not recognized as an internal or external command

Cause: The JDK bin directory is not in the PATH environment variable.

Fix:

# Windows: System Properties → Environment Variables → add to Path
%JAVA_HOME%\bin

# Or use the direct path
C:\Program Files\Eclipse Adoptium\jdk-21.0.2.13-hotspot\bin

Error 2: JAVA_HOME is not set

Cause: Build tools (Maven, Gradle) cannot find the JAVA_HOME environment variable.

Fix:

# Windows
setx JAVA_HOME "C:\Program Files\Eclipse Adoptium\jdk-21.0.2.13-hotspot"

# macOS/Linux (add to ~/.zshrc or ~/.bashrc)
export JAVA_HOME=/usr/lib/jvm/temurin-21

Error 3: Error: Could not find or load main class

Cause 1: Running from the wrong directory when a package is declared

# Wrong (when a package exists)
java HelloWorld

# Correct (run from the source root)
java com.example.HelloWorld

Cause 2: Including the .class extension

# Wrong
java Hello.class

# Correct
java Hello

Error 4: class HelloWorld is public, should be declared in a file named HelloWorld.java

Cause: The filename does not match the public class name (including case).

Fix: Rename the file to match the class name exactly.

Error 5: UnsupportedClassVersionError

Error: LinkageError occurred while loading main class Hello
java.lang.UnsupportedClassVersionError: Hello has been compiled by a more
recent version of the Java Runtime (class file version 65.0), this version
of the Java Runtime only recognizes class file versions up to 55.0

Cause: Compiled with a newer JDK than the JRE used to run it (e.g., compiled with Java 21, running with Java 11).

Fix: Upgrade the runtime JDK version to match or exceed the compilation version.


9. Environment Setup Checklist

Once installation is complete, verify all of the following:

# 1. Check JDK version
java -version
# → Should output openjdk version "21.x.x"

# 2. Check compiler version
javac -version
# → Should output javac 21.x.x

# 3. Check JAVA_HOME
echo %JAVA_HOME% # Windows
echo $JAVA_HOME # macOS/Linux
# → Should output the JDK installation path

# 4. Quick compile and run test
echo public class Test { public static void main(String[] a) { System.out.println("OK"); } } > Test.java
javac Test.java && java Test
# → Should output: OK

If all items pass, your development environment is fully configured!

tip

Using IntelliJ IDEA? The IDE auto-detects your JDK. Confirm at File → Project Structure (Ctrl + Alt + Shift + S) → Project SDK that JDK 21 is selected.


Summary

StepAction
Step 1Download and install JDK 21 LTS (Eclipse Temurin recommended)
Step 2Set JAVA_HOME environment variable and update PATH
Step 3Verify with java -version and javac -version
Step 4Install an IDE (IntelliJ IDEA Community recommended)
Step 5Write, compile, and run your first Hello World program