Setup Java JDK in macOS
By sborrazas on 2024-06-12
Updated version:
I use mise now. So I just have to do brew install mise && mise install java@23
to get java 23.
Old post:
I use fish shell and VSCodium (a fork of VS Code without telemetry).
- Install Homebrew https://brew.sh/
- Install fish with
brew install fish
- This guide is for fish shell, so be sure to continue in fish shell by running
fish
. Optionally, you can set fish as your default shell on macOS - Install openjdk with
brew install openjdk
- After installing openjdk, I get the following caveat text from Homebrew (which you can read again by running
brew info openjdk
):
For the system Java wrappers to find this JDK, symlink it with
sudo ln -sfn /opt/homebrew/opt/openjdk/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk.jdk
openjdk is keg-only, which means it was not symlinked into /opt/homebrew,
because macOS provides similar software and installing this software in
parallel can cause all kinds of trouble.
If you need to have openjdk first in your PATH, run:
fish_add_path /opt/homebrew/opt/openjdk/bin
For compilers to find openjdk you may need to set:
set -gx CPPFLAGS "-I/opt/homebrew/opt/openjdk/include"
- Run
fish_add_path /opt/homebrew/opt/openjdk/bin
to be able to runjavac
- Run
/usr/libexec/java_home -V
to get theJAVA_HOME
of the installed jdks. Mine returns:
Matching Java Virtual Machines (1):
21.0.2 (arm64) "Homebrew" - "OpenJDK 21.0.2" /opt/homebrew/Cellar/openjdk/21.0.2/libexec/openjdk.jdk/Contents/Home
/opt/homebrew/Cellar/openjdk/21.0.2/libexec/openjdk.jdk/Contents/Home
- To set
JAVA_HOME
environment variable, runset -Ux JAVA_HOME /opt/homebrew/opt/openjdk/libexec/openjdk.jdk/Contents/Home
. You can check this is a symlink to the installed jdk withls -lart /opt/homebrew/opt/openjdk
- Create a file called Hello.java with the following content:
public class Hello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
- Run
javac Hello.java
which will create a file calledHellow.class
. Then you can runjava Hello
to run your new class (beware this command takes the class name, not the filename). The output of the command isHello, World!
- Now that you have the java development kit up and running in your computer, it’s time to get some IDE support to get auto-completion, auto-import, etc. You can choose between Eclipse, IntelliJ, VS Code, etc. In my personal computer I use VSCodium. Install VSCodium with
brew install vscodium
(orvisual-studio-code
if you prefer) - You can open VSCodium from the terminal with
codium .
. Search for extensions in VSCodium and install Extension Pack for Java which installs several convenient extensions for working with Java. I started with Language Support for Java™ by Red Hat but it misses some functionality, so my recommendation is to go for the extension pack - Congratulations! You got your Java development environment ready. You might want to install maven with
brew install maven