Setting Up the Java Development Environment

A Java environment is easier to set up than it looks and harder to diagnose than it should be, because most of the confusion comes from three things that people assume are one thing: the compiler, the runtime, and the build tool. They are separate programs, they are installed in separate places, and each of them can be a different version. Once you know which of the three a message is talking about, every setup problem becomes a simple lookup. By the end of this page you will have a JDK installed and verified, JAVA_HOME and PATH pointing at the right directory, an IDE configured to use it, and a Maven or Gradle project that builds from a clean checkout.

1. What the toolchain actually contains

A modern JDK ships a surprising number of executables, but four of them carry almost all of the daily work. They all live in the bin directory of the JDK, which is why PATH matters so much.

CommandWhat it doesWho needs it
javacCompiles .java source files into .class bytecode filesAnyone who writes Java
javaStarts the JVM and runs a compiled classAnyone who runs Java
jshellAn interactive REPL that evaluates Java statements on the spotAnyone learning or exploring
jarPackages classes and resources into .jar archivesAnyone shipping a library

Two more show up once a project exists: javap disassembles a compiled class so you can see its signatures, and javadoc generates API documentation from specially formatted comments.

The execution model is the part worth understanding before installing anything, because it explains why the tools are separate. Java source is compiled to bytecode, an intermediate instruction set that is specific to the Java platform but not to any particular processor. The bytecode runs on a Java Virtual Machine, and that machine is responsible for translating bytecode into native instructions for the machine underneath. This is the mechanism behind the “write once, run anywhere” promise: the same .class file runs on every platform that has a JVM, and each platform supplies its own JVM to do the final translation.

The consequence for you is simple. javac and java must agree about the bytecode version they speak, and a bytecode file produced by a newer compiler cannot be executed by an older runtime. Almost every “Unsupported class file major version” error in a Java career is this mismatch.

2. JDK and JRE: the distinction that dissolved

For years Java shipped in two boxes. The JRE (Java Runtime Environment) contained the JVM and the class libraries: everything needed to run Java, and nothing to compile it. The JDK (Java Development Kit) contained the JRE plus the compiler and the developer tools. The rule was blunt: you ran applications on a JRE, you built applications on a JDK.

That split is history. Oracle stopped publishing a standalone JRE installer after Java 10, and the separate jre directory was removed from the JDK layout in Java 11. From Java 11 onward the JDK is the only supported distribution, and the supported way to produce a small runtime for deployment is to build one yourself with jlink.

jlink --module-path "$JAVA_HOME/jmods" \
      --add-modules java.base,java.sql \
      --output build/runtime

The result is a directory that contains a trimmed JVM and just the modules your application needs. It is smaller than a full JRE ever was, and it is produced from the same JDK you already have.

The practical guidance for a developer is short. Install a JDK. The “JRE only” installers that still circulate are either ancient (Java 8 era) or stripped-down runtimes such as the one inside a JRE-shaped container image. Neither contains javac, and neither can build anything.

3. Choosing a distribution and a version

The JDK is an open specification, and several organisations ship builds of it. The differences are in support policy, update cadence, and licensing, not in the language.

DistributionWhat it isA good reason to pick it
Eclipse TemurinThe reference open-source build, produced by the Adoptium projectThe default choice for most people: free, vendor-neutral, quick updates
Oracle JDKOracle’s own build of the same specificationEnterprise agreements that already include Oracle support
Amazon CorrettoAmazon’s build of OpenJDK, published free of charge with a long-term support policyRunning on AWS and wanting a distribution with a predictable support life
Microsoft Build of OpenJDKMicrosoft’s build, used across Azure and .NET shopsMicrosoft-centric estates, including WSL images
Azul ZuluA commercial vendor with a very wide platform matrixNeeding a build for an unusual platform or a specific support SLA

Any of them will teach you Java identically. Pick one, and prefer to use the same one on every machine in a team, because mixed distributions make version problems harder to read.

Version choice matters more than distribution choice. Oracle publishes a release every six months and marks every second one as Long Term Support (LTS), which means it receives security and stability updates for years rather than until the next release arrives.

ReleaseYearStatus
Java 82014LTS, still widely deployed
Java 112018LTS
Java 172021LTS
Java 212023LTS
Java 252025LTS, the most recent long-term release

The releases in between, such as Java 20 or Java 22, are feature releases. They are excellent for experimenting and they are a poor choice for a production service, because their support window closes when the next release lands.

For this course, Java 17 and Java 21 are both good targets. Java 17 is the version a large part of the existing enterprise estate runs on; Java 21 is the current long-term release and is the one most new projects should standardise on. Java 21 is also the first release in which the “virtual threads” preview matured into a permanent feature, which is one reason it became the popular starting point.

4. Installing the JDK

On macOS, Homebrew installs a versioned package, and the prefix it reports is exactly the directory JAVA_HOME should point at.

brew install openjdk@21
export JAVA_HOME="$(brew --prefix openjdk@21)"
export PATH="$JAVA_HOME/bin:$PATH"

On Linux, the system package manager is the shortest path, and SDKMAN is the most convenient one when you will need several versions.

# Debian and Ubuntu
sudo apt update && sudo apt install openjdk-21-jdk

# SDKMAN, which also manages Maven, Gradle and other JVM tools
curl -s "https://get.sdkman.io" | bash
sdk install java 21.0.5-tem

On Windows, the winget identifier is stable, and the MSI installer works if you prefer a graphical path.

winget install Microsoft.OpenJDK.21
[Environment]::SetEnvironmentVariable("JAVA_HOME", "C:\Program Files\Java\jdk-21", "User")

Whatever route you take, write the JAVA_HOME value into the shell profile rather than typing it every time, and remember that a profile change does not affect shells that are already open.

5. Verifying the installation

Verification is three commands, and each one rules out a different failure. Run them in a freshly opened shell.

java -version
javac -version
which java

A healthy installation prints something like this:

openjdk version "21.0.5" 2024-10-15 LTS
OpenJDK Runtime Environment Temurin-21.0.5+11 (build 21.0.5+11-LTS)
OpenJDK 64-Bit Server VM Temurin-21.0.5+11 (build 21.0.5+11-LTS, mixed mode, sharing)

The first line tells you the version and whether it is a long-term release. The second names the vendor and the build, which is what you paste into a bug report when something behaves differently on another machine.

If java -version works but javac -version does not, you have installed a runtime rather than a JDK. If which java prints a path that does not live under the directory you expected, an older Java is shadowing the one you just installed, and that is the problem to fix first.

jshell deserves a quick check too, because it is the fastest way to confirm that the compiler, the runtime and the class libraries agree with each other.

jshell
jshell 21.0.5
|  Welcome to JShell 21.0.5
|  For an introduction type '?'

Type System.out.println("ready"); and press Enter. If the words appear, your toolchain is coherent.

6. JAVA_HOME and PATH

These two variables do different jobs, and mixing them up is the most common configuration mistake.

PATH is a list of directories that the shell searches when you type a command name. It is what lets java and javac work at all. JAVA_HOME is a single directory that programs read to find the whole JDK, including parts that are not on the PATH at all, such as the include directory used by native tools and the jmods directory used by jlink.

The rule is therefore simple:

  • PATH must contain $JAVA_HOME/bin.
  • JAVA_HOME must contain bin, lib, include and jmods. It points at the JDK root, never at the bin directory itself.

On macOS and Linux, the profile fragment looks like this:

export JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64
export PATH="$JAVA_HOME/bin:$PATH"

macOS ships a helper that resolves installed versions and rejects the ones you did not ask for:

/usr/libexec/java_home -V          # list every installed JDK
export JAVA_HOME=$(/usr/libexec/java_home -v 21)

On Windows, JAVA_HOME is set through the environment variable dialog or the command shown earlier, and PATH receives %JAVA_HOME%\bin.

Maven, Gradle, IntelliJ IDEA, and many other tools read JAVA_HOME to decide which JDK to run on, while your shell resolves javac through PATH. If the two disagree, the build and the shell are using different Java versions, and the symptom is a class file that compiles cleanly and then fails to run.

7. Configuring an IDE

An IDE does not contain its own Java. It uses the JDK you install, so the first configuration step is always the same: tell the IDE which JDK the project should use.

IntelliJ IDEA. Open the project, then choose File → Project Structure → Project, set the SDK to your JDK 21 installation, and set the language level to 21. Check Settings → Build, Execution, Deployment → Build Tools → Maven and Gradle separately, because each build tool has its own idea of which JDK to use and that setting can differ from the project SDK. IntelliJ can also download a JDK for you through the SDK Manager, which is convenient but worth understanding, because it produces a second installation that your shell does not know about.

Eclipse. The JDK is chosen under Preferences → Java → Installed JREs, and the project level is set under Java Build Path → Libraries. Eclipse also needs a JRE Container entry under Java Build Path, which is the piece that beginners most often forget.

Visual Studio Code. Install the Extension Pack for Java, which brings the Language Support for Java and Debugger for Java extensions. Then set java.configuration.runtimes in settings.json, mapping a name to the path of your JDK, and set java.jdt.ls.java.home so the language server itself runs on the right version.

{
  "java.configuration.runtimes": [
    { "name": "JavaSE-21", "path": "/usr/lib/jvm/java-21-openjdk-amd64" },
    { "default": true, "name": "JavaSE-21" }
  ]
}

In every IDE, the setting worth checking after the first build is the one that decides which JDK runs the build. IntelliJ shows it in the project SDK, Eclipse in the JRE container, and VS Code in the Maven and Gradle extension settings.

8. Maven

Maven is a build tool defined by a convention. You describe what your project contains and what it depends on, in a single XML file called pom.xml (Project Object Model), and Maven works out the rest: which directories hold sources, in what order compilation happens, which plugins run in which phase, and where the resulting artifact is written.

A project is identified by three coordinates: a group identifier, an artifact identifier, and a version. com.example:order-service:1.0.0 says that the order-service artifact, version 1.0.0, belongs to the com.example group.

The build is organised as a lifecycle of phases, and you invoke a phase rather than a task.

PhaseWhat it does
validateChecks that the project description is well formed
compileCompiles the main sources
testRuns the unit tests
packageBuilds the artifact, a JAR by default
verifyRuns the checks that need the packaged artifact, such as integration tests
installCopies the artifact into the local repository
deployPublishes the artifact to a remote repository

The commands you will actually type:

mvn -v                                  # Maven version and the JDK it runs on
mvn clean compile                       # recompile from scratch
mvn test                                # run the tests
mvn -Dtest=OrderServiceTest test        # run one test class
mvn package                             # produce target/demo-1.0.0.jar
mvn install                             # install into ~/.m2/repository
mvn dependency:tree                     # show the resolved dependency graph
mvn help:effective-pom                  # print the fully expanded POM
mvn exec:java -Dexec.mainClass=com.example.App   # run a main class

Maven creates a project from a template, and the quickstart archetype is the one to use:

mvn archetype:generate \
  -DgroupId=com.example \
  -DartifactId=demo \
  -DarchetypeArtifactId=maven-archetype-quickstart

9. Gradle

Gradle is also a build tool, but it is task driven rather than phase driven. Instead of a fixed lifecycle, the build file declares tasks and the relationships between them, and Gradle works out the execution order, skipping work whose inputs have not changed.

A Gradle project is created and initialised with:

mkdir demo && cd demo
gradle init --type=java
gradle wrapper --gradle-version 9.0.0

The wrapper is the important part of that second command. It writes gradlew, gradlew.bat and a gradle/wrapper/gradle-wrapper.properties file into the project, so the whole team builds with the exact Gradle version the project declares. Always use ./gradlew rather than a globally installed gradle, because the wrapper is what makes a build reproducible.

The commands:

./gradlew build              # compile, test, and assemble
./gradlew test               # run the tests only
./gradlew run                # run the application plugin main class
./gradlew tasks              # list every task in the project
./gradlew dependencies       # show the resolved dependency tree
./gradlew clean build        # rebuild from a clean state
./gradlew build --info       # verbose output for diagnosing failures
./gradlew --stop             # stop the background Gradle daemon

Gradle keeps a daemon process running in the background so that each build does not have to start a new JVM and re-read the whole model. That is why the first build of a session is slower than the second.

10. Maven or Gradle?

Both tools can build the same project. They differ in where they put the emphasis.

AspectMavenGradle
ModelDeclarative XML, fixed lifecycle phasesProgrammatic build logic, custom task graph
Configuration languageXML onlyGroovy DSL or Kotlin DSL
Incremental buildsBasicFine grained, per task
Build cacheAvailable in recent versionsBuilt in, including remote caching
Configuration cacheAvailable in recent versionsBuilt in, enabled by default in recent versions
Learning curveVery low, the conventions do the workLower at first for simple builds, higher once logic grows
Best fitLarge teams that value uniformityProjects that need custom build logic or faster local iteration

If a team already uses one of them, use that one. If you are choosing from scratch for a small service, Maven is the smaller thing to learn, because most of its behaviour is a convention you never have to write down. If you expect to customise the build heavily or you want the fastest possible local iteration, Gradle is the better fit.

11. A project on disk

Maven and Gradle use the same directory layout by default, which means the structure below works with either tool.

demo/
├── pom.xml                  # or build.gradle / build.gradle.kts
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/example/App.java
│   │   └── resources/
│   └── test/
│       ├── java/
│       │   └── com/example/AppTest.java
│       └── resources/
└── target/                  # or build/, created by the tool

A minimal pom.xml that compiles with Java 21:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>demo</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <packaging>jar</packaging>

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

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>5.11.0</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

The release property is worth understanding rather than copying. It tells the compiler to target that language and API level, and it also checks that you did not use any API newer than it. Using source and target instead would compile against a newer class library while claiming an older version, which produces bytecode that fails at runtime with NoSuchMethodError.

The equivalent Gradle build file, in the Kotlin DSL:

plugins {
    java
    application
}

group = "com.example"
version = "1.0.0-SNAPSHOT"

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(21))
    }
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:5.11.0")
}

application {
    mainClass.set("com.example.App")
}

Build and run it:

mvn clean package && java -jar target/demo-1.0.0.jar
./gradlew build && ./gradlew run

12. Managing several JDK versions

Real teams run several Java versions at once: an old service on Java 8, a new service on Java 21, and a build that has to support both. Two approaches handle this well.

Toolchains let a build request a specific JDK regardless of the one running the build. Maven reads ~/.m2/toolchains.xml, and Gradle has a first-class toolchain block, as shown above.

<?xml version="1.0" encoding="UTF-8"?>
<toolchains>
  <toolchain>
    <type>jdk</type>
    <provides>
      <version>21</version>
      <vendor>temurin</vendor>
    </provides>
    <configuration>
      <jdkHome>/usr/lib/jvm/temurin-21-jdk</jdkHome>
    </configuration>
  </toolchain>
</toolchains>

Version managers keep several installations on disk and switch between them. SDKMAN handles this well on macOS and Linux, and jenv is a lighter alternative that only manages the JAVA_HOME value.

sdk list java                 # what is available
sdk use java 17.0.13-tem     # switch for this shell
sdk default java 21.0.5-tem  # switch for new shells

13. Common setup problems

SymptomCauseFix
java: command not foundPATH does not contain the JDK bin directoryAdd export PATH="$JAVA_HOME/bin:$PATH" to your profile and open a new shell
java -version works, javac -version failsA runtime was installed instead of a JDKInstall a JDK and repoint JAVA_HOME at it
error: JAVA_HOME is set to an invalid directoryJAVA_HOME points at the bin directory instead of the JDK rootRemove the trailing bin from the value
The shell and the build use different Java versionsPATH and JAVA_HOME disagree, or an older JDK comes first in PATHRun which -a java and fix the ordering
Unsupported class file major versionA class compiled by a newer JDK is running on an older JVMCompile with --release matching the target runtime, or run on the newer JVM
release version 21 not supportedThe compiler on PATH is older than 21Repoint PATH at a Java 21 JDK
Maven downloads dependencies on every buildThe local repository at ~/.m2/repository is missing or read onlyCheck the path and permissions of the local repository
Gradle build fails with a class file errorThe Gradle JVM and the toolchain are different versionsSet the toolchain in the build file and use the wrapper

With the environment verified, the next chapter takes the smallest possible program and follows it through the compiler and the virtual machine, so that nothing about the toolchain stays a mystery.

javafundamentals

Approach:

A working Java environment is not a single fact but a set of independent ones: a compiler that exists, a runtime that exists, a version that the two agree on, a build tool that runs on that same version, and an IDE that points at the same JDK. Each of them can fail on its own, and a failure in one of them often looks like a failure in another. The approach here is therefore to install one thing (a JDK, never a JRE), verify it with the smallest possible set of commands that each rule out a different fault, then wire the environment variables and the build tool so that every layer points at the same installation.

Steps:

  1. Choose a distribution and a version before installing anything. Pick an LTS release, Java 21 for new work or Java 17 for an existing estate, and a well-known open build such as Eclipse Temurin unless your organisation already standardises on something else.
  2. Install the JDK, then verify it in a freshly opened shell with java -version, javac -version and which java. If the runtime works but the compiler does not, you installed a JRE and the fix is to install a JDK instead.
  3. Set JAVA_HOME to the JDK root, the directory that contains bin, and put $JAVA_HOME/bin on PATH. Confirm both with echo "$JAVA_HOME" and which -a java, and make sure only one JDK appears first in the list.
  4. Check the compiler with jshell: type a System.out.println statement and confirm the output appears, which proves the compiler, the runtime and the class libraries agree.
  5. Configure the IDE to use the same JDK, and separately check the JDK setting that the build tool integration uses, since IntelliJ IDEA, Eclipse and VS Code each keep that setting in a different place.
  6. Choose a build tool. Maven is the smaller thing to learn because its conventions do most of the work; Gradle is the better fit when the build needs custom logic or faster local iteration. Whichever you choose, generate the project and commit the wrapper or the POM.
  7. Lay the project out with sources under src/main/java and tests under src/test/java, with the package directory structure mirroring the package name.
  8. Build and run the project end to end, then confirm the artifact runs outside the build tool with java -jar target/demo-1.0.0.jar.

Answer:

After this chapter the environment produces these results:

  • java -version prints a version line such as openjdk version "21.0.5" 2024-10-15 LTS, followed by the runtime and virtual machine lines naming the vendor build.
  • javac -version prints javac 21.0.5, which confirms a full JDK rather than a runtime is installed.
  • echo "$JAVA_HOME" prints the JDK root, for example /usr/lib/jvm/java-21-openjdk-amd64, and which java prints the java executable inside that root’s bin directory.
  • jshell starts, evaluates System.out.println("ready");, and prints ready, which shows the toolchain is internally consistent.
  • mvn -v and ./gradlew --version both report Java 21, so the build tool and the shell agree on the runtime.
  • mvn clean package and ./gradlew build both succeed, and the resulting JAR starts with java -jar.

When all six hold, the environment is not merely installed but coherent, and the next chapter can concentrate on the language itself.

Found an issue with this content?

Tell us what could be improved.