Download Article
Easy ways to set the JAVA_HOME environment variable
Download Article
- Windows
- Mac
- Linux
- Video
- Tips
|
|
|
|
Are you seeing Java errors like «JAVA_HOME is not defined correctly?» or «JAVA_HOME is set to an invalid directory?» If you’ve recently installed the Java Development Kit (JDK), you’ll need to set your JAVA_HOME variables and configure the path so applications know where to find Java. This wikiHow article will show you the easiest ways to change or set the Java home path on Windows, macOS, and Linux.
Setting Java Home: Fast Facts
- To set JAVA_HOME, you’ll need the full path to your JDK or JRE installation.
- On Windows, you’ll set JAVA_HOME in Advanced System Settings > Environment Variables.
- On a Mac, you’ll need to add the Java path to your .zshrc file in a Terminal.
- On Linux, you can add the Java path to your .bashrc.
-
Assuming that you didn’t change the path for the JDK during installation, it should be in a directory under C:\Program Files\Java. There are a few ways to find the full path:
- Open File Explorer, click This PC in the left panel, then navigate to C:\Program Files\Java. The directory you’re looking for should have the name of the JDK version, such as C:\Program Files\Java\jdk-23.
- You can also open the command prompt and run the command wmic product where "Name like '%%Java%%'" get installlocation,Name. This will tell you the full path of the JDK, even if you haven’t yet set JAVA_HOME.
-
Here’s how:
- Press the Windows key on your keyboard and type advanced system.
- Click View advanced system settings in the search results.
Advertisement
-
You’ll see it at the bottom-right corner of the System Properties window.
-
You’ll have two sections on this window—»User variables» and «System variables.» You’ll want to make sure you’re clicking New under the first box (User variables).
- If you have multiple JDK installations and want to change JAVA_HOME to your new installation, select the current JAVA_HOME user variable and click Edit… instead.
-
- If you’re editing the current JAVA_HOME path, you’ll already have JAVA_HOME here. So, you can skip this step.
-
For example, if the path is C:\Program Files\Java\jdk-23, enter that full path into the «Variable value» field.[1]
- If you’re adding a second path to JAVA_HOME, just type a semicolon (;) after the first path, then enter the second path.
- If you’re replacing an old JAVA_HOME path, just delete the current path and enter the new one.
-
This takes you back to the Environment Variables window.
-
You should already have a variable in the «User variables» section called «Path.» To make sure you can run the Java binaries, you’ll need to edit your path to add the location of the JDK bin directory.
- If you want other users on this PC to be able to access Java binaries from the command line, repeat this step for the «Path» variable under «System variables» as well.
-
You’ll already have at least one directory in your path, which needs to stay in place. Here’s how to add the Java bin directory:
- Click the New button at the top.
- Enter the full path to the JDK with \bin at the end. For example, C:\Program Files\Java\jdk-23.0.2\bin.
- Click OK.
-
This updates your JAVA_HOME variable and adds the Java binaries to your path.
- You won’t need to restart your computer for the changes to take effect, but you will need to relaunch any apps that were trying to access Java.
- Open a new command prompt window and run the command echo %JAVA_HOME% to display the new path to JAVA_HOME.
- Make sure this is a new command prompt window. If you still have the same window open, the command will fail because it doesn’t have the new environment variables.
Advertisement
-
To open Terminal, search for Terminal in Spotlight. You can also open Finder, click the Go menu, select Utilities, and choose the Terminal app.
-
This handy utility that comes preinstalled on macOS will tell you the full path to your Java installation, which you’ll need to set JAVA_HOME.
- If you have more than one Java installation and want to see the paths to all of them, use /usr/libexec/java_home -V instead.
-
Highlight the path to the Java installation you want to use as JAVA_HOME, press Cmd + V to copy it, then paste it into a sticky note or text file.
-
As long as you’re using macOS Catalina or later, you’ll be using the zsh shell by default, which means you’ll add JAVA_HOME and the path to your .zshrc file.[2]
If you’re using an earlier version of macOS (or prefer the bash shell), replace .zshrc with .bashrc in these commands instead. Here’s the easiest way to open the file:- Type cd ~ and press Return.
- Type open .zshrc and press Return. This should open the file in a text editor.
- If the file is not found, type echo > .zshrc and press Return. Then, run open .zshrc again.
-
Adding these lines ensures that JAVA_HOME will be set correctly even after you log off or open another window. If the file has existing contents, just scroll down past them to enter the following text on individual lines:
-
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-23.0.2.jdk/Contents/Home
- Replace
/Library/Java/JavaVirtualMachines/jdk-23.0.2.jdk/Contents/Home
with the full path to the /Contents/Home directory of your Java installation if it’s different.
- Replace
export PATH=$JAVA_HOME/bin:$PATH
- Save the file and exit the text editor when you’re finished.
-
-
Once you’ve edited your profile, this command ensures that your environment variables will be updated for the current terminal window (and any other windows you open from now on).
-
You should now see the full path to JAVA_HOME.
- If you have any other open windows attempting to find Java binaries, close and reopen them.
Advertisement
-
If you’re logged in to your desktop environment, you can press Ctrl + Alt + T to launch a terminal window.
- This method will work in just about any version of Linux, including Ubuntu and Redhat.
-
One way you might find the Java install location is to run the which javac command, but this will only give you a symbolic link. Instead, run this command to find the location of the executable file:
- readlink -f `which javac`
- If that doesn’t work, try running update-alternatives --list java.
- If neither of these commands works, run whereis java, which will usually result in a symbolic link like /usr/bin/java.
- Once you get the directory, find out where it links using ls -la /bin/java.
- If that points you to another directory, e.g., /etc/alternatives/java, run ls -la /etc/alternatives/java.
- At that point, you should see a much longer directory, which is actually the home to the Java binaries. For example, usr/lib/jvm/java-23-openjdk-arm64/bin/java. This is the directory you want.
-
Now that you have the location of Java, you can add the path to your .bashrc file (if you’re using the bash shell), .zshrc (for the zsh shell), or the equivalent for your shell.[3]
Run both of the following commands, replacing the path with the path to your JDK or JRE installation, and «bashrc» with your shell’s login script:echo "export JAVA_HOME=/usr/lib/jvm/java-23-openjdk-arm64" >> ~/.bashrc
echo "export PATH=$PATH:$JAVA_HOME/bin" >> ~/.bashrc
-
Though you’ve already set the home for Java and added the path to its binaries permanently, the changes won’t take effect in your current terminal window until you run this command.
- At this point, you can run echo $JAVA_HOME to see the location of Java on your system.
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Video
-
In Linux, you can set JAVA_HOME for all users by editing the global .bashrc, which is located at /etc/bash.bashrc. Just use echo and replace ~/.bashrc with /etc/bash.bashrc.
-
On both Linux and macOS, you can set the Java home in your .bash_profile or .zprofile if you prefer.
Thanks for submitting a tip for review!
Advertisement
About This Article
Thanks to all authors for creating a page that has been read 378,581 times.
Is this article up to date?
Переменная окружения JAVA_HOME – это один из ключевых параметров, необходимых для работы множества инструментов, таких как Gradle, Maven, Tomcat, Android Studio и других. Если она не настроена или указана неправильно, многие приложения могут не запускаться, а сборка проектов – выдавать ошибки.
Эксперты рекомендуют
Что такое JAVA_HOME?
– это переменная окружения, которая указывает системе путь к установленному JDK. Она необходима для правильной работы различных инструментов разработки, компиляторов, серверных приложений.
Чем отличается от PATH?
JAVA_HOME хранит путь к установленному JDK и помогает программам находить нужную версию.
PATH содержит список директорий, в которых система ищет исполняемые файлы. Если в PATH не указан путь, команда может не работать.
Почему важно правильно настроить JAVA_HOME?
Если переменная не настроена, система может использовать устаревшую или неподходящую версию. Это приводит к ошибкам при запуске приложений, проблемам с компиляцией и сбоям в работе инструментов сборки.
Настройка позволяет избежать таких проблем и обеспечивает корректную работу всех зависимых программ.
Как определить, задана ли переменная?
Windows:
Открыть Командную строку. Ввести команду: echo %JAVA_HOME%. Если не задана, отобразится пустая строка или сообщение об ошибке.
macOS и Linux:
Открыть Терминал. Ввести команду: echo $JAVA_HOME. Если не настроена, вывод будет пустым.
Настройка в Windows
1. Найдите путь к установленному JDK
Откройте Проводник и перейдите в папку: C:\Program Files\Java. Внутри этой директории найдите папку с установленной версией. Откройте папку и скопируйте полный путь.
2. Добавление
- Откройте Панель управления.
- Перейдите в Система → Дополнительные параметры.
- Нажмите Переменные.
- В разделе Системные переменные нажмите Создать.
- В поле Имя введите: JAVA_HOME
- В поле Значение вставьте скопированный ранее путь.
- Нажмите ОК.
3. Добавление в PATH
В списке Системные переменные найдите Path. Нажмите Изменить → Создать. Вставьте: %JAVA_HOME%\bin. Сохраните изменения.
4. Проверка
Откройте Командную строку (cmd) и введите: java -version. Если все прошло успешно, отобразится установленная версия.
Настройка в macOS, Linux
1. Найдите путь
Выполните команду: /usr/libexec/java_home. Она отобразит путь к установленному JDK, например.
2. Установка
Откройте файл конфигурации: nano ~/.zshrc. Добавьте строку: export JAVA_HOME=$(/usr/libexec/java_home). Сохраните файл и обновите настройки.
3. Проверка настройки
Выполните команду: echo $JAVA_HOME. Если путь отображается корректно, настройка завершена.
Как автоматизировать выбор версии?
Если на вашей системе установлено несколько вариантов JDK, можно настроить автоматический выбор нужной версии с помощью утилит, таких как SDKMAN! для Linux и macOS, или с помощью JEnv. Эти инструменты позволяют легко переключаться без необходимости вручную редактировать переменную.
Преимущества использования SDKMAN! или JEnv:
- Простота в переключении между версиями JDK.
- Удобство работы с несколькими версиями для различных проектов.
- Автоматическая настройка.
- Поддержка множества инструментов и фреймворков
- Простота в обновлениях
- Удобный интерфейс командной строки
Как выбрать подходящую версию для проекта?
1. Требования проекта:
Для различных фреймворков и библиотек могут понадобиться разные версии. Например, JDK 8 подходит для старых приложений, а для современных технологий лучше выбрать JDK 11 или 17.
2. LTS:
Если проект требует долгосрочной поддержки, выбирайте LTS, которые обеспечат стабильность и регулярные обновления безопасности.
3. Тестирование:
Тестирование на нескольких версиях поможет убедиться, что все компоненты работают корректно. Инструменты, такие как SDKMAN! или JEnv, позволяют легко переключаться между версиями.
4. Преимущества новых версий:
Новые JDK предлагают улучшения в производительности и поддержке многозадачности, что полезно для приложений с высокими требованиями.
Сравнение установки в разных ОС
Настройка в разных ОС имеет свои особенности, связанные с управлением переменными окружения. В таблице ниже представлена детальная информация о процессе настройки.
ОС |
Где установить |
Файл конфигурации |
Как обновить |
Требуется ли перезагрузка? |
Windows | Панель управления → Система → Дополнительные параметры → Переменные | Отдельного файла конфигурации нет, настройки хранятся в Переменных Windows | Перезапустить терминал | Да (для применения изменений во всех программах) |
macOS | Файл ~/.zshrc (для zsh) или ~/.bash_profile (для bash) | ~/.zshrc (для zsh) или ~/.bash_profile (для bash) | source ~/.zshrc или source ~/.bash_profile | Нет, достаточно обновить конфигурацию с помощью source |
Linux | Файл ~/.bashrc или ~/.bash_profile | ~/.bashrc (для текущего пользователя) или /etc/profile (для всех пользователей) | source ~/.bashrc | Нет, достаточно обновить конфигурацию |
Почему в Windows требуется перезагрузка?
После изменения переменных окружения в Windows многие приложения и терминалы продолжают использовать старые конфигурации. Перезагрузка ОС гарантирует, что все программы увидят обновленный вариант. В macOS и Linux достаточно выполнить команду source ~/.bashrc или source ~/.zshrc, чтобы изменения вступили в силу.
Ошибки и способы их устранения
Большинство ошибок связаны с некорректными путями или забытыми конфигурациями. Важно указывать путь, добавлять в PATH, а после изменений перезапускать терминал. Соблюдение этих рекомендаций обеспечит стабильную работу приложений.
1. Система сообщает, что переменная не задана:
Отсутствует либо указана неправильно, поэтому система не может ее найти. Проверьте, зарегистрирована ли в окружении. Если значение пустое, добавьте путь. В Windows потребуется перезагрузка, в macOS и Linux – перезапуск терминала.
2. Указан неверный путь:
Часто ссылается на JRE вместо JDK, содержит ошибки или устарел после обновления. Определите актуальную директорию и укажите ее, избегая ссылок на JRE или bin.
3. Команда ‘java’ не распознается:
Отсутствует в PATH, поэтому система не может найти исполняемый файл. Добавьте bin из JDK в PATH через конфигурации среды, затем перезапустите терминал. В Windows может потребоваться перезагрузка.
4. Пробелы:
Некоторые инструменты не поддерживают пути с пробелами, например, *C:\Program Files\Java* в Windows.
Используйте кавычки либо короткий формат.
5. Используется не та версия:
При наличии нескольких версий система может обращаться к устаревшей. Определите активную, убедитесь, что путь ведет к нужной, обновите настройки, затем перезапустите терминал.
6. Изменения не вступают в силу:
Система продолжает использовать старые значения, поскольку обновления не применились. Закройте и откройте терминал заново. В Windows возможна необходимость перезагрузки, в macOS и Linux – обновления конфигурации.
7. Настроена, но система не работает:
Путь указан неверно, JDK не установлен или отсутствует в PATH. Проверьте наличие Java, убедитесь, что путь правильный, при необходимости добавьте в PATH.
Реальная история успеха
Илья, начинающий разработчик, столкнулся с проблемой при компиляции приложений: несмотря на установленный JDK, система не могла найти Java. Он понял, что проблема заключалась в отсутствии переменной. После настройки все заработало, и проект был успешно завершён. Через несколько месяцев Илья устроился в IT-компанию, где занимается разработкой серверных приложений и теперь помогает коллегам с настройкой окружения.
Заключение
Настройка JAVA_HOME – это важный шаг для работы с приложениями. Без правильно заданной переменной окружения многие инструменты могут работать некорректно или не запускаться вовсе. Настроив систему один раз, можно избежать множества проблем и сосредоточиться на разработке.
Setting the `JAVA_HOME` environment variable in Windows 10 is a crucial step for a Java developer to run Java applications on their computer. Here are the steps to set up the `JAVA_HOME` variable in Windows 10:
1. Download and install the latest version of Java SE Development Kit (JDK) from Oracle’s website.
2. After installing the JDK, open the «System Properties» window, which can be reached by right-clicking on «This PC» and selecting «Properties.«
3. Click on the «Advanced system settings» option from the left panel, which opens the «System Properties» window. Go to the «Advanced» tab and click on the «Environment Variables» button.
4. In the «Environment Variables» window, locate the «System Variables» section and click on the «New» button below it.
5. In the «New System Variable» window, set the variable name as `JAVA_HOME` and variable value as the installation path of your JDK. For example: `C:\Program Files\Java\jdk-16.0.1` (This path may differ based on the version of JDK installed on your computer)
6. Click the «OK» button to save the `JAVA_HOME` environment variable.
7. Now, locate the `Path` environment variable from the «System Variables» section and click on the «Edit» button.
8. In the «Edit Environment Variable» window, click the «New» button and enter `%JAVA_HOME%\bin` in the text field.
9. Click on the «OK» button to save the new path.
10. Close all the windows and open a new command prompt window. Type `java -version` and press enter to verify that the JDK is configured correctly.
By following these steps, you’ll be able to set up the `JAVA_HOME` environment variable on your Windows 10 computer and run Java applications without any issues.
How do I set my JAVA_HOME?
Setting the JAVA_HOME environment variable is necessary for many Java-based applications to run properly on a machine. To set the JAVA_HOME on a Windows machine, follow these steps:
1. Open the Start menu and search for «Environment Variables«. Click on «Edit the system environment variables«.
2. In the «System Properties» window, click on the «Environment Variables…» button.
3. Under «System Variables«, scroll down and click on «New«.
4. In the «New System Variable» window, type «JAVA_HOME» in the «Variable name» field and the path to your JDK installation directory in the «Variable value» field. For example, «C:\Program Files\Java\jdk1.8.0_281«.
5. Click «OK» to close all windows.
To set the JAVA_HOME on a Unix/Linux machine, follow these steps:
1. Open a terminal window.
2. Type «sudo nano /etc/environment» and press Enter.
3. Add the line «JAVA_HOME=/usr/lib/jvm/[your JDK version]» (without quotes). Replace «[your JDK version]» with the name of your JDK installation directory.
4. Press Ctrl+X to exit, then Y to save changes, and Enter to confirm the file name.
5. Type «source /etc/environment» to apply the changes to the current session, or restart the machine to apply the changes system-wide.
How to set up JAVA_HOME in Windows?
JAVA_HOME is a system environment variable that specifies the root directory location where Java Development Kit (JDK) is installed on your computer. Follow the instructions below to set up JAVA_HOME in Windows:
1. Install JDK on your computer and remember the installation directory path.
2. Open the Windows Control Panel, then select System and Security.
3. Select System and click on the Advanced system settings link.
4. In the System Properties window, click on the Environment Variables button.
5. Under the System Variables section, scroll down and look for the JAVA_HOME variable. If it is already present, select it, and click on the Edit button, and update the variable value to the installation directory path of the JDK.
6. If it is not present, click on the New button and enter JAVA_HOME in the Variable name field and enter the installation directory path of the JDK in the Variable value field. For instance, if your JDK has been installed in «C:\Program Files\Java\jdk1.8.0_201«, then you would enter «C:\Program Files\Java\jdk1.8.0_201» in the Variable value field.
7. Click OK and close all open windows.
By setting up JAVA_HOME in Windows, you ensure that other Java-based tools and applications know where to look for the Java Development Kit (JDK) whenever it is required to run.
How to set JAVA_HOME and Jre_home in Windows 10?
Setting the JAVA_HOME and JRE_HOME environment variables in Windows 10 allows various applications and services to access the Java Development Kit (JDK) and Java Runtime Environment (JRE) installed on your computer. To set these variables in Windows 10, follow these steps:
1. Open the Control Panel and select System.
2. Click on Advanced system settings.
3. Click on the Environment Variables button located at the bottom right of the window.
4. Under the System Variables section, click New.
5. In the Variable Name field, enter JAVA_HOME and in the Variable Value field, type the path of your JDK installation folder (for example, C:\Program Files\Java\jdk1.8.0_221).
6. Click OK to close the variable window.
7. Repeat steps 4-6 and add another environment variable named JRE_HOME. For the Variable Value field, type the path of the JRE installation folder (for example, C:\Program Files\Java\jre1.8.0_221).
8. Click OK to close all the windows.
By setting these environment variables, you’ll now be able to use Java from any command prompt or terminal window, without having to constantly type out the full path to the executables.
How to find JAVA_HOME path in Windows 10?
JAVA_HOME is an environment variable that is used to point to the location where Java is installed on your computer. To find JAVA_HOME in Windows 10, follow the steps below:
1. Open the Start menu and search for «System.» Click on the «System» app to open it.
2. On the left-hand side of the System app, click on «Advanced system settings.«
3. A «System Properties» window will open. Click on the «Environment Variables» button at the bottom.
4. In the «System Variables» section, scroll down until you find «JAVA_HOME.» If it is already set, you will see the path to the Java installation directory.
5. If you do not see «JAVA_HOME,» click on the «New» button and add the variable name as «JAVA_HOME» and set its value to the path where Java is installed on your system. For example, if you installed Java in «C:\Program Files\Java\jdk1.8.0_291,» then set the value to «C:\Program Files\Java\jdk1.8.0_291.«
6. Click «OK» to close all the windows and save your changes.
Now you know the process of finding JAVA_HOME path in Windows 10.
How to set JAVA_HOME path and classpath?
Setting the JAVA_HOME path and classpath is essential to run Java programs and applications correctly. The JAVA_HOME path is an environment variable that points to the location of the Java Development Kit (JDK) on your computer. The classpath is another environment variable that specifies the location of Java libraries, classes, and resources that your Java programs need to access.
To set the JAVA_HOME path and classpath, follow these steps:
1. Download and install the latest version of the JDK appropriate for your system.
2. Locate the installation directory where the JDK was installed on your computer. For example, on Windows, it is usually installed in «C:\Program Files\Java\«.
3. Set the JAVA_HOME path by going to your system’s environment variables and adding a new variable named JAVA_HOME with the directory path where the JDK is installed (e.g. «C:\Program Files\Java\jdk-16«).
4. Set the classpath by adding the directory paths of the Java libraries and classes to the CLASSPATH variable in the environment variables (e.g. «C:\Program Files\Java\jdk-16\lib«).
Once you have set the JAVA_HOME path and classpath, your Java programs can access the necessary Java libraries and classes for their proper execution.
How to set JAVA_HOME in the class path?
Setting the JAVA_HOME environment variable allows an application to locate the Java Development Kit (JDK) on a system. Setting the class path directs the Java Virtual Machine (JVM) to search for classes in specified directories or JAR files. To set JAVA_HOME in the class path, you need to first determine the location of your JDK installation. Once you have located the JDK installation directory, set the JAVA_HOME environment variable to this directory. Then, append the path to the bin directory within your JAVA_HOME directory to the class path. This can be done using the following command:
`export JAVA_HOME=/path/to/JDK`
`export PATH=$JAVA_HOME/bin:$PATH`
This will set the JAVA_HOME variable and append the bin directory to the system path. This ensures that Java commands could be executed as well as Java classes can be found by the Java Virtual Machine.
How to set Java home with JRE?
To set the Java home with JRE, you need to follow the following steps:
1. Determine the path of your JRE location.
2. Open the Environment Variables dialog box on your Windows system.
3. Under the “System Variables” section, click the “New” button.
4. In the “New System Variable” dialog box, enter “JAVA_HOME” in the “Variable Name” field.
5. In the “Variable Value” field, enter the path of your JRE installation directory.
6. Click the “OK” button to save the changes.
7. Locate the “Path” variable under the “System Variables” section and click the “Edit” button.
8. In the “Edit Environment Variable” dialog box, append the following at the end of the existing value:
%JAVA_HOME%\bin;
9. Click the “OK” button to save the changes.
10. Restart your system to apply the changes.
After these steps, the Java home with JRE should be set on your system.
Before showing you how to set JAVA_HOME on all the operation systems, let’s explain what is an environment variable? And what is the use of JAVA_HOME environment variable?
- Set JAVA_HOME on Windows
- Set JAVA_HOME on Windows 10 and 8
- Windows 7
- Verifying JAVA_HOME configuration
- Set JAVA_HOME on Mac OS X
- Mac OS X 10.5 or Newer — Single user
- Mac OS X Older Versions
- Global Setting
- Set JAVA_HOME on Linux
- Single User
- Global Setting
- Conclusion
As a prerequisite you will need to have a installed JDK or JRE on your machine. See for details in article Install JDK aka Java SDK
As you probably know, almost all java code has a variable that stores a value which is used many times in a program. An environment variable is like a final variable (in java) but for your environment. So, JAVA_HOME is a environment variable used to point to the directory where JRE or JDK is installed in your environment.
Let’s go right to the point. So how to set JAVA_HOME on Windows, Mac os, and Linux?
1. Set JAVA_HOME on Windows
There are two ways to configure JAVA_HOME on windows depending on which version you have (windows 10, 8 or 7). In order to set JAVA_HOME environment variable, please follow below steps.
1.1. Set JAVA_HOME on Windows 10 and 8
To set JAVA_HOME on windows 10/8, you need to follow these steps below:
- Search for «advanced system settings» on windows Search
Searching for «advanced system settings». - Then, select «View advanced system settings» in the shown options
Selecting «View advanced system settings». - Now you need to click on «Environment Variables» under the Advanced tab
Under «Advanced», selecting «Environment Variables». - Click on «New (or User variables for single user)» in the System variables section
New system variable. - In this step, you will have to set JAVA_HOME as the Variable name and in the Variable value you will have to give the path to JDK installation, then click OK
Adding the system variable. - To finish the configuration, click OK then Apply to save changes
1.2. Windows 7
Configuring the environment variable on windows 7 is little bit different. Below the steps.
- On the Start menu or on the desktop, right-click on «My computer» and then select «Properties«
- Click on «Environment Variables» under the Advanced tab
- Click on «New (or User variables for single user)» in the System variables section
- Now, set JAVA_HOME as the Variable name and as the Variable value, the path to JDK installation, then click OK
- Click OK then Apply to save and apply changes
1.3. Verifying JAVA_HOME configuration
To verify that you correctly set the JAVA_HOME environment variable, open Command prompt (windows + R) and check JAVA_HOME variable’s value:
echo %JAVA_HOME%
If you have rightly configure JAVA_HOME, the result should be similar to the following:
C:\Program Files\JAva\jdk-12
2. Set JAVA_HOME on Mac OS X
Setting the JAVA_HOME environment variable on Mac OS is little bit different from configuring it on windows. To do so, all you need is to follow the steps described below.
2.1. Mac OS X 10.5 or Newer — Single user
Since OS X 10.5 was revealed, Apple added a command line tool (/usr/libexec/java_home) which dynamically finds for the current user, the top java version specified in Java Preferences.
Let’s start by opening ~/.bash_profile in any text editor and add:
export JAVA_HOME=$(/usr/libexec/java_home)
Then, save and close the file.
On the Terminal, run the following source command to apply all the changes.
source ~/.bash_profile
At this point, you can check JAVA_HOME variable’s value using:
echo $JAVA_HOME
Below the expected result (jdk installation path)
/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home
2.2. Mac OS X Older Versions
Before OS X 10.5, you had to set the exact path to the JDK installation. If you have the concerned version of Mac Os, you need to to open ~/.bash_profile in any editor and add:
export JAVA_HOME=/path/to/java_installation
Then, save and close the file.
On the Terminal, run the following source command to apply all the changes.
source ~/.bash_profile
At this point, you can check JAVA_HOME variable’s value using:
echo $JAVA_HOME
Below the expected result (jdk installation path)
/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home
2.3. Global Setting
Instead of setting JAVA_HOME for a single user, you can configure it globally by following the same steps as for single user except that you will have to use the file /etc/profile.
3. Set JAVA_HOME on Linux
On linux, there are two ways to set the JAVA_HOME environment variable. Below steps for configuring for both single user or globally.
3.1. Single User
To configure JAVA_HOME for a single user in Linux, you need to use /etc/profile or /etc/environment (system-wide setting or ~/.bashrc (user specific setting).
Now you need to open ~/.bashrc in your text editor using:
vi ~/.bashrc
and add:
export JAVA_HOME=/path/to/java_installation
To apply changes, save and close the file.
Next step, you will have to run the source command to load the variable using the following:
source ~/.bashrc
To verify the JAVA_Home value, use:
echo $JAVA_HOME
And the result should be something similar to the following (the path of JDK installation):
/usr/lib/jvm/java-8-oracle
3.2. Global Setting
I personally prefer to set the JAVA_HOME globally for all users using:
/etc/profile
or
/etc/environment
So you have to open /etc/environment in any text editor using:
vi /etc/environment
and add:
JAVA_HOME=/path/to/java_installation
NB: /etc/environment is not a script. It represents a list of assignment which are read at the time of login.
To set the environment variable JAVA_HOME, you need to open /etc/profile and add in it:
export JAVA_HOME=/path/to/java_installation
Then run the source command in order to load the variable using:
source /etc/profile
Of course, you need to check JAVA_HOME variable’s value at the end of the configuration using:
echo $JAVA_HOME
And the result should be something similar to (the path of the JDK installation):
/usr/lib/jvm/java-8-oracle
PS: Please note that these steps are also valid for Ubuntu OS. All that you need to verify, is to check where is java installed by:
which java
Then, follow the steps described above.
4. Conclusion
To summarize, we’ve covered in today’s article, the steps that you need to follow to configure JAVA_HOME environment variable correctly in your environment (windows, mac os, and linux).
JAVA_HOME environment variable referring to JDK installed directory before bin. Learn how to set JAVA_HOME Linux or JAVA_HOME Windows, get JAVA_HOME envrionment variable and set path.
When you install JDK in your system either Windows, Linux or UNIX, it creates a home directory and puts all its binary under bin folder, library under lib folder, and other utility tools. After setting JAVA_HOME and path environemnt variable $path=$JAVA_HOME/bin
, you can access those utilty like javac or java
etc from anywhere in your computer. You can How to install Oracle JDK 8 on Ubuntu , if you have not installed in your system.
Step by Step process in Windows 7/8/10 as follows:
- Right click your My Computer icon on your desktop and select Properties.
- Click the Advanced tab.
- Click the Environment Variables button.
- Under System Variables, click New. ( you can set for logged-in user but preferebale is system variable so that any another user can get those variable)
- Enter variable name as JAVA_HOME.
- Enter variable value (one of the paths mentioned above) as the installation path for the JDK (Java Development Kit) before bin folder. e.g C:\JDK7\jdk1.7.0_65 ( I installed under JDK7 in side the c drive, I have changed this folder while installation)
- Click OK button.
- Click Apply Changes.
Once you set JAVA_HOME environment variable you have to set path as well, if you want to run utility from command prompt from any location.
2. JAVA_HOME environment Variable in Windows Temporarily
open commond prompt by typing cmd on run commnd.
set JAVA_HOME=C:\JDK7\jdk1.7.0_65
check by following command on command prompt.
echo %JAVA_HOME%
3. JAVA_HOME environment Variable in Unix/Linux
There are multiple place where you can edit and put following line of
open the vi $HOME/.bashrc
or vi $HOME/.bash_profile
or vi /etc/profile
vim ~/.bashrc
and place following line to set JAVA_HOME
export JAVA_HOME=/opt/JDK7/jdk1.7.0_65
Check it by following command on command prompt.
source ./profile echo $JAVA_HOME
4. How to get JAVA_HOME environment in Java
While development sometimes if you have to get JAVA_HOME environemnt in java code, you can get by following way. it means, use java.home is Java system property and you can access it on java code using System.getProperty("java.home")
.
you can access java.home
inside apache ANT as ${java.home}
Java program to get JAVA_HOME env
package com.mysoftkey.core; /** * get JAVA_HOME environment variable in java. * * @author ranjeet jha * */ public class JavaHomeExample { public static void main(String[] args) { String java_home = System.getProperty("java.home"); System.out.println("JAVA_HOME : " + java_home); } }
Output of Java_home Program
Either you set JAVA_HOME Linux or JAVA_HOME Windows you can get environent variable using above piece of code.
JAVA_HOME : C:\JDK7\jre7
5. Reference
you can visit Java tutorial for more details
you can visit Oracle java for more details
Your comments/suggestions are welcome to improve this post of setting JAVA_HOME environment variable either in Linux or Windows.
Happy Learning! 🙂