Java how to set java home
Java how to set java home
Переменная окружения JAVA_HOME
Во многих статьях в интернете, документации к инструментам для разработки на Java и в книгах зачастую упоминается JAVA_HOME. Что же такое JAVA_HOME?
Что такое JAVA_HOME
JAVA_HOME это переменная окружения, указывающая на директорию с установленным JDK (Java Development Kit, комплект разработчика Java). JAVA_HOME это соглашение, используемое во многих программах из экосистемы Java.
Какие программы используют JAVA_HOME
Некоторые игры, написанные на Java (например, Minecraft), тоже могут требовать установленной переменной JAVA_HOME.
Ошибки, связанные с JAVA_HOME
Если переменная окружения JAVA_HOME не определена, некоторые программы могут выдавать следующие ошибки:
При появлении таких ошибок просто установите переменную JAVA_HOME
Как установить переменную окружения JAVA_HOME в Windows
Сперва вам нужно установить JDK или JRE.
После установки JDK либо JRE запишите путь установки, он понадобится.
Теперь щёлкните правой кнопкой на «Мой компьютер» → «Свойства» → «Дополнительные параметры системы» → «Переменные среды…». В разделе «Системные переменные» нажмите кнопку «Создать…» и укажите следующие данные:
Имя переменной | JAVA_HOME |
Значение переменной | Путь к директории JDK / JRE, например: C:\Java\jdk-11.0.6 |
Сохраните изменения, кликнув «OK». Теперь выберите в списке переменную окружения Path и нажмите «Изменить…». В конце списка добавьте строчку со значением «%JAVA_HOME%\bin«
Для проверки откройте консоль (Win+R, cmd) и укажите последовательно укажите две команды:
Если вы правильно установили JDK/JRE и правильно установили переменные окружения, вы увидите вывод наподобие этого:
Это будет служить результатом того, что переменная JAVA_HOME установлена правильно и Java работает из командной строки.
Резюме
В данной статье мы рассказали вам, что являет собой переменная окружения JAVA_HOME, где она используется и как её корректно указать.
How to set JAVA_HOME in Windows and echo the result
Set JAVA_HOME properly and echo your results with the following tidbits, and also examine how a proper PATH installation can benefit your local environment.
If you plan to run software programs like Maven, Jenkins, Gradle or Tomcat, you’ll not only need a local installation of the JDK, but you’ll also want to ensure that you have set JAVA_HOME correctly. Here is how you can accomplish that task with a demonstration of how to set JAVA_HOME in Windows and echo the result to validate that the changes have gone into effect. Also, let’s explore how you can add Java to the Windows PATH, which is another configuration parameter that is often set after a JDK installation.
Three ways to set the JDK JAVA_HOME variable in Windows include:
Not every Java installer will automatically set JAVA_HOME for you. The AdoptOpenJDK one will, and it can configure the PATH variable for you as well. But, it doesn’t do it all by default. You must perform a custom install and select one of the following two options to have the OpenJDK installer set JAVA_HOME and PATH environment variables:
That’s all there is to it. Once the OpenJDK installation is complete, the JAVA_HOME variable will be configured and the bin directory of the JDK will be added to the Windows PATH. It doesn’t get much easier than that.
If your JDK installation didn’t set JAVA_HOME automatically, you can always open the Windows environment variable editor and set it yourself. This is the easiest way to manually set JAVA_HOME in Windows 7, 8 and 10.
Follow these steps to manually set JAVA_HOME:
After you add the new environment variable, close any and all DOS prompts and command windows, because these tools load environment variables only when they first start. If you try to access the JAVA_HOME variable in any windows that were open prior to the change, the variable will come back as null or undefined. But if you open a new command window, scripts that search for JAVA_HOME will run successfully.
The third way to configure the Windows JAVA_HOME environment variable is to use the command line and invoke the setx command as follows:
As you can see, the setx JAVA_HOME approach is relatively simple. Still, command line interface tools can intimidate some people, and this type of manual coding is prone to error. However, when you write scripts to automate the configuration of the environment, the ability to script the process with setx becomes invaluable.
After you set JAVA_HOME in Windows, it’s a good idea to verify that the change has persisted. The easiest way to do this is to echo JAVA_HOME in a command prompt or a BASH shell.
To echo JAVA_HOME in a Windows DOS prompt or command window, you simply bookend the variable with percentage signs:
@REM How to echo JAVA_HOME in windows
echo %JAVA_HOME%
>> C:\_jdk12.0
The manner in which you get JAVA_HOME within batch files and shell scripts follows the exact same syntax used by the echo command. Bookend the variable with percentage signs and use that variable within your code just as you would any other scripted variable.
Scripts that use JAVA_HOME should always be checked to see if the variable exists. If it does not, an appropriate error message will arise. Here is how the Apache Maven project gets JAVA_HOME in its startup script and reports any errors during the process:
@REM Apache Maven JAVA_HOME Startup Script
@REM ==START JAVA_HOME VALIDATION ==
if not «%JAVA_HOME%»==»» goto OkJHome
for %%i in (java.exe) do set «JAVACMD=%%
$PATH:i»
goto checkJCmd
:OkJHome
set «JAVACMD=%JAVA_HOME%\bin\java.exe»
:checkJCmd
if exist «%JAVACMD%» goto chkMHome
echo JAVA_HOME environment variable is not defined correctly >&2
echo This environment variable is needed to run this program >&2
echo NB: JAVA_HOME should point to a JDK not a JRE >&2
goto error
The JAVA_HOME and PATH environment variables serve two very different purposes. JAVA_HOME simply points to where Java is installed. If you add something to the PATH variable, it makes it available throughout the entire operating system. Of course, many developers who install Java actually want the runtime universally available, so they set the JAVA_HOME and PATH environment variables at the same time.
The big distinction between PATH and JAVA_HOME settings is that the former points to the JDK bin directory, while the latter points to the installation directory. Developers are notorious for mixing up these two settings, which invariably leads to program start issues and the subsequent JAVA_HOME error messages such as «java_home is set to an invalid directory» or «java_home environment variable is not set.»
How to add the JDK bin directory to the Windows PATH.
When you add the JDK \bin directory to the PATH, you can specify the absolute path, or you can get clever and reference the JAVA_HOME environment variable as so:
%JAVA_HOME% bin
It is worth noting that while a JDK installation is linked to the JAVA_HOME environment variable, JRE installations are typically linked to the JRE_HOME variable. The steps to set up JRE_HOME on a Windows machine are exactly the same as those outlined above, with the exception that the JRE_HOME variable will point to the root of the JRE installation, while the JAVA_HOME environment variable in Windows points to the root of the JDK installation.
How do I install Java?
How do I install Java on Ubuntu?
How do I install Java on Windows?
Full GitHub Actions environment variables list for YAML build workflow scripts example
Microsoft’s Azure Advisor service offers recommendations based on five categories. Learn these categories and the roles they play.
Researchers with Palo Alto Networks took the stage at Black Hat to explain how configurations and system privileges in Kubernetes.
How to set JAVA_HOME properly?
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?
Table of Contents
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:
1.2. Windows 7
Configuring the environment variable on windows 7 is little bit different. Below the steps.
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:
If you have rightly configure JAVA_HOME, the result should be similar to the following:
Verifying «JAVA_HOME».
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.
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:
Then, save and close the file.
On the Terminal, run the following source command to apply all the changes.
At this point, you can check JAVA_HOME variable’s value using:
Below the expected result (jdk installation path)
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:
Then, save and close the file.
On the Terminal, run the following source command to apply all the changes.
At this point, you can check JAVA_HOME variable’s value using:
Below the expected result (jdk installation path)
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:
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:
To verify the JAVA_Home value, use:
And the result should be something similar to the following (the path of JDK installation):
3.2. Global Setting
I personally prefer to set the JAVA_HOME globally for all users using:
So you have to open /etc/environment in any text editor using:
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:
Then run the source command in order to load the variable using:
Of course, you need to check JAVA_HOME variable’s value at the end of the configuration using:
And the result should be something similar to (the path of the JDK installation):
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:
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).
How to set JAVA_HOME in Linux for all users
I am new to Linux system and there seem to be too many Java folders.
Could you please tell me which files I need to modify for root as well as not-root user and where exactly is java located?
22 Answers 22
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Prepend sudo if logged in as not-privileged user, ie. sudo vim
For all users, I would recommend creating a file in /etc/profile.d/java_home.sh the following lines
This will update dynamically and works well with the alternatives system. Do note though that the update will only take place in a new login shell.
You could use /etc/profile or better a file like /etc/profile.d/jdk_home.sh
None of the other answers were «sticking» for me in RHEL 7, even setting JAVA_HOME and PATH directly in /etc/profile or
/.bash_profile would not work. Each time I tried to check if JAVA_HOME was set, it would come up blank:
What I had to do was set up a script in /etc/profile.d/jdk_home.sh :
I initially neglected the first line (the #!/bin/sh ), and it won’t work without it.
Now it’s working:
/.bash_profile and used this approach.
It will ask you your password. After typing the password, it will open the bash file. Then go to end and type:
Then save the file and exit from file
Above is for a single user. For all users, you have to follow below steps
Copy the bin file path you installed
open terminal and edit environment file by typing following command,
In this file, add the following line (replacing YOUR_PATH by the just copied path):
That should be enough to set the environment variable. Now reload this file:
now test it by executing:
Doing what Oracle does (as a former Sun Employee I can’t get used to that one)
then export JAVA_HOME=/usr/java/default
The answer is given previous posts is valid. But not one answer is complete with respect to:
So as stated above create /etc/profile.d/custom.sh file for custom changes.
Now, to always keep updated with newer versions of Java being installed, never put the absolute path, instead use:
#if making jre as java home
First you need to find out which Java is installed in your PC and which one to use. For that open terminal with root permission.
Now it will list the available java versions. Select the listed version.
Copy the path till there.
Now open bashrc
add the following commands to the end
after that save the file and exit by pressing Ctrl+S followed by Ctrl+X
Now run the below command:
1. Using the short cut Ctlr + Alt + T to open terminal
2. Execute the below command:
3. (Recommended) Restart your VM / computer. You can use source /etc/source if don’t want to restart computer
4. Using the short cut Ctlr + Alt + T to open terminal
5. Verified JAVA_HOME installment with
One-liner copy from flob, credit to them
This is a very simple script to solve the problem
And for testing:
Posting as answer, as I don’t have the privilege to comment.
Point to note: follow the accepted answer posted by «That Dave Guy».
After setting the variables, make sure you set the appropriate permissions to the java directory where it’s installed.
All operational steps(finding java, parent dir, editing file. ) one solution
1) Let’s break the full command into pieces
2) Find java path from java command
3) Get relative path from symbolic path
4) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java
5) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/
Probably a good idea to source whatever profile you edit to save having to use a fresh login.
Where is whatever profile you edited.
On Linux I add this line to my
While we are up to setting JAVA_HOME, let me share some benefits of setting JAVA_HOME or any other environment variable:
1) It’s easy to upgrade JDK without affecting your application startup and config file which points to JAVA_HOME. you just need to download new version and make sure your JAVA_HOME points to new version of Java. This is best benefit of using environment variable or links.
2) JAVA_HOME variable is short and concise instead of full path to JDK installation directory.
Installing the JDK Software and Setting JAVA_HOME
If you do not already have the JDK software installed or if the JAVA_HOME environment variable is not set, the GlassFish ESB installation will not be successful. The following tasks provide the information you need to install the JDK software and set JAVA_HOME on UNIX or Windows systems.
Caution –
The GlassFish ESB Installer does not support JDK release 1.6.0_04 in the 64–bit version on the Solaris SPARC or AMD 64–bit environments.
To Install the JDK Software and Set JAVA_HOME on a UNIX System
To install the JDK software, do the following:
Select the appropriate JDK version and click Download.
The JDK software is installed on your computer in the default location; for example, at /usr/jdk/jdk1.6.0_02. You can change this location.
To set JAVA_HOME, do one of the following:
For Korn and bash shells, run the following commands:
export JAVA_HOME= jdk-install-dir
For the bourne shell, run the following commands:
For the C shell, run the following commands:
setenv JAVA_HOME jdk-install-dir
Change the permissions to enable you to run the GlassFish ESB Installer by running the following command:
chmod 755 JavaCAPS.bin
To Install the JDK Software and Set JAVA_HOME on a Windows System
To install the JDK software, do the following:
Select the appropriate JDK software and click Download.
The JDK software is installed on your computer in the default location; for example, at C:\Program Files\Java\jdk1.6.0_02. You can move the JDK software to another location.
To set JAVA_HOME, do the following:
Right click My Computer and select Properties.
On the Advanced tab, select Environment Variables, and then edit JAVA_HOME to point to where the JDK software is located, for example, C:\Program Files\Java\jdk1.6.0_02.
Источники информации:
- http://www.theserverside.com/feature/How-to-set-JAVA_HOME-in-Windows-and-echo-the-result
- http://xenovation.com/blog/development/java/how-to-set-java-home
- http://stackoverflow.com/questions/24641536/how-to-set-java-home-in-linux-for-all-users
- http://docs.oracle.com/cd/E19182-01/821-0917/inst_jdk_javahome_t/index.html