How to set JAVA_HOME in Mac permanently?
in stackoverflow ∙
2 mins read
∙ Tags: Java, Macos, Java-home
Last modified at:
Updated:
How to set JAVA_HOME in Mac permanently?
Question by Vishal Tavande
I am trying to set JAVA_HOME
by entering export JAVA_HOME=/Library/Java/Home
at terminal. It sets the JAVA_HOME
for current session.
How can I set it permanently?
Answer by Milovan Tomašević
Installing Java on macOS 11 Big Sur
:
- the easiest way is to select OpenJDK 11 (LTS), the HotSpot JVM, and macOS x64 is to get the latest release here: adoptopenjdk.net
- Select macOS and x64 and download the
JDK
(about 190 MB), which will put theOpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.pkg
file into your~/Downloads folder
- Clicking on pkg file, will install into this location:
/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk
- Almost done. After opening a terminal, the successful installation of the JDK can be confirmed like so:
java --version
- output:
openjdk 11.0.9.1 2020-11-04
OpenJDK Runtime Environment AdoptOpenJDK (build 11.0.9.1+1)
OpenJDK 64-Bit Server VM AdoptOpenJDK (build 11.0.9.1+1, mixed mode)
JAVA_HOME
is an important environment variable and it’s important to get it right. Here is a trick that allows me to keep the environment variable current, even after a Java Update was installed. In~/.zshrc
, I set the variable like so:export JAVA_HOME=$(/usr/libexec/java_home)
- In previous macOS versions, this was done in
~/.bash_profile
. Anyway, open a new terminal and verify:echo $JAVA_HOME
- output:
/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home
- output:
TEST: Compile and Run your Java Program
- Open a text editor, copy the code from below and save the file as
HelloStackoverflow.java
.// file: 'test.java' public class HelloStackoverflow { public static void main(String[] args){ System.out.println("Hello Stackoverflow !"); }//End of main }//End of HelloStackoverflow Class
- From a terminal set the working directory to the directory containing
HelloStackoverflow.java
, then type the command:
# file: 'terminal'
javac HelloStackoverflow.java
-
If you’re lucky, nothing will happen
-
Actually, a lot happened.
javac
is the name of the Java compiler. It translates Java intoJava Bytecode
, an assembly language for the Java Virtual Machine (JVM). The Java Bytecode is stored in a file calledHelloStackoverflow.class
. -
Running: type the command:
# file: 'terminal'
java HelloStackoverflow
# output:
# Hello Stackoverflow !
Improve this page:
Share on:
Keep going!
Keep going ×2!
Give me more!
Thank you, thank you
Far too kind!
Never gonna give me up?
Never gonna let me down?
Turn around and desert me!
You're an addict!
Son of a clapper!
No way
Go back to work!
This is getting out of hand
Unbelievable
PREPOSTEROUS
I N S A N I T Y
FEED ME A STRAY CAT
Share on:
Comments 💬
Templates (for web app):
Loading…
Permalink