Install Java on macOS
Step by Step Instructions
Steps to Install Java on macOS
In this guide, we go through step by step instructions to install Java on your Mac.
Step 1: Check if Java is Already Installed
macOS often comes with a version of Java pre-installed. To check what you have, open your Terminal and type:
java -version
If Java is already installed, you'll see an output like this:
java version "17.0.2" 2022-01-18 LTS
Java(TM) SE Runtime Environment (build 17.0.2+8-LTS-86)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.2+8-LTS-86, mixed mode, sharing)
If not installed, you’ll get prompted with something like:
No Java runtime present, requesting install.
Step 2: Install Homebrew (If Not Installed)
Homebrew is the preferred package manager for macOS, making Java installation much smoother. Run this in your Terminal to install Homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
After installation, verify that brew
is available:
brew --version
Step 3: Install Java Using Homebrew
Now that Homebrew is ready, let's install the latest version of Java:
brew install openjdk
This installs the latest OpenJDK version. You may also install a specific version like Java 17:
brew install openjdk@17
Step 4: Configure Your Shell to Use Java
After installation, you need to link Java binaries so your shell can recognize them. If you're using zsh
(default in newer macOS), add this to your ~/.zprofile
:
echo 'export PATH="/opt/homebrew/opt/openjdk/bin:$PATH"' >> ~/.zprofile
source ~/.zprofile
Or for Bash users:
echo 'export PATH="/opt/homebrew/opt/openjdk/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile
Step 5: Confirm Java Installation
After setup, confirm your Java version again:
java -version
openjdk version "21.0.1" 2023-10-17
OpenJDK Runtime Environment Homebrew (build 21.0.1)
OpenJDK 64-Bit Server VM (build 21.0.1, mixed mode)
Step 6: Write and Run Your First Java Program
Let’s write a basic Java program to verify everything works.
Create a File
touch HelloWorld.java
open -a TextEdit HelloWorld.java
Paste This Code
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Java is successfully installed!");
}
}
Compile and Run
javac HelloWorld.java
java HelloWorld
Java is successfully installed!
Frequently Asked Questions
Q. Can I install multiple Java versions on macOS?
Yes, using brew install openjdk@11
or @17
, etc. You can then switch between them using tools like jenv
or manual PATH exports.
Q. What is the difference between Oracle JDK and OpenJDK?
Oracle JDK is distributed by Oracle with some commercial features. OpenJDK is an open-source implementation, widely used and supported, and perfect for development.