Explain Codes LogoExplain Codes Logo

How to set JAVA_HOME in Linux for all users

java
java-home
linux
environment-variables
Anton ShumikhinbyAnton Shumikhin·Sep 8, 2024
TLDR

To define JAVA_HOME for all users, tweak /etc/environment:

sudo sh -c 'echo JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64 >> /etc/environment'

To activate changes:

source /etc/environment

Or, set via /etc/profile.d creating a java_home.sh script:

sudo sh -c 'echo "export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64" > /etc/profile.d/java_home.sh'

Check with:

echo $JAVA_HOME && echo $PATH

Locating the Java installation directory

Java's installation may differ. Locate it this way:

find /usr/lib/jvm/ -name "java-*" -type d # When you see too many Java versions, you know you're a serious Java-holic.

Reflect the correct JAVA_HOME in previous steps.

Instantly updating JAVA_HOME

To apply modifications without relogging:

source /etc/profile # Feel free to yell "Eureka!".

For dynamically setting JAVA_HOME, add this to java_home.sh:

export JAVA_HOME=$(readlink -f /usr/bin/javac | sed 's:/bin/javac::') # This is like having your cake and eating it too. 😋

This keeps JAVA_HOME updated even post Java-upgrade.

Handling multiple versions of Java

If dealing with multiple Java incarnations, use update-alternatives managing symlinks to versions, pairing it with setting JAVA_HOME to:

update-alternatives --config java # Because variety is the spice of life, right?

Ensuring script's permissions

Scripts in /etc/profile.d/ require executable permissions:

sudo chmod +x /etc/profile.d/java_home.sh # Because scripts too need their "armors".

This ensures all users get Java environments.

Sync across profiles for uniform experience

JAVA_HOME has to be identical in .bashrc and /etc/profile for seamless user experience. To tweak .bashrc:

echo "export JAVA_HOME=$JAVA_HOME" >> ~/.bashrc echo "export PATH=$PATH:$JAVA_HOME/bin" >> ~/.bashrc source ~/.bashrc # Congratulations, you just created an echo-chamber.

This caters to interactive shells and user-specific bases.

Managing Java and Maven together

An incorrect JAVA_HOME can fire up Maven build errors. Check your Maven pointing to JAVA_HOME:

mvn -version # Fingers crossed! 🤞

It should resonate with Java path in JAVA_HOME.