Windows set java home command line

If you are a windows user, you may have come across situations like you need to set  environment veriables like JAVA_HOME but not having enough permission to access “Advanced system settings&…

Skip to content

If you are a windows user, you may have come across situations like you need to set  environment veriables like JAVA_HOME but not having enough permission to access “Advanced system settings” option where you can dirrectly change them using the wizard or throught the “registry editor”.

But setx program can resolve your problem as it helps you to change environment valiable though Command Prompt

The setx command is similar to the UNIX utility SETENV.

See below example

C:>setx JAVA_HOME <PATH>

When we set the variable

C:>setx JAVA_HOME "C:Program FilesJavajdk1.6.0_26"
SUCCESS: Specified value was saved.

Note
When you change an environment variable by using the Windows setx command, you must close and reopen the Command Prompt window for the change to take effect.

We can check value of the set variable

C:>echo %JAVA_HOME%
C:Javajdk1.6.0_26

Resource

http://technet.microsoft.com/en-us/library/cc755104(v=ws.10).aspx

We need to make a distinction between the two environment variables that are discussed here interchangeably. One is the JAVA_HOME variable. The other is the Path variable. Any process that references the JAVA_HOME variable is looking for the search path to the JDK, not the JRE. The use of JAVA_HOME variable is not meant for the Java compiler itself. The compiler is aware of its own location. The variable is meant for other software to more easily locate the compiler. This variable is typically used by IDE software in order to compile and build applications from Java source code. By contrast, the Windows CMD interpreter, and many other first and third party software references the Path variable, not the JAVA_HOME variable.

Use case 1: Compiling from CMD

So for instance, if you are not using any IDE software, and you just want to be able to compile from the CMD, independent of your current working directory, then what you want is to set the Path variable correctly. In your case, you don’t even need the JAVA_HOME variable. Because CMD is using Path, not JAVA_HOME to locate the Java compiler.

Use case 2: Compiling from IDE

However, if you are using some IDE software, then you have to look at the documentation first of all. It may require JAVA_HOME to be set, but it may also use another variable name for the same purpose. The de-facto standard over the years has been JAVA_HOME, but this may not always be the case.

Use case 3: Compiling from IDE and CMD

If in addition to the IDE software you also want to be able to compile from the CMD, independent of your current working directory, then in addition to the JAVA_HOME variable you may also need to append the JDK search path to the Path variable.

JAVA_HOME vs. Path

If your problem relates to compiling Java, then you want to check the JAVA_HOME variable, and Path (where applicable). If your problem relates to running Java applications, then you want to check your Path variable.

Path variable is used universally across all operating systems. Because it is defined by the system, and because it’s the default variable that’s used for locating the JRE, there is almost never any problem running Java applications. Especially not on Windows where the software installers usually set everything up for you. But if you are installing manually, the safest thing to do is perhaps to skip the JAVA_HOME variable altogether and just use the Path variable for everything, for both JDK and the JRE. Any recent version of an IDE software should be able to pick that up and use it.

Symlinks

Symbolic links may provide yet another way to reference the JDK search path by piggybacking one of the existing environment variables.

I am not sure about previous versions of Oracle/Sun JDK/JRE releases, but at least the installer for jdk1.8.0_74 appends the search path C:ProgramDataOracleJavajavapath to the Path variable, and it puts it at the beginning of the string value. This directory contains symbolic links to the java.exe, javaw.exe and javaws.exe in the JRE directory.

So at least with the Java 8 JDK, and presumably the Java 8 JRE standalone, no environment variable configuration needs to be done for the JRE. As long as you use the installer package to set it up. There may be differences on your Windows installation however. Note that the Oracle JRE comes bundled with the JDK.

If you ever find that your Java JDK configuration is using the wrong version of the compiler, or it appears to be working by magic, without being explicitly defined so (without casting the spell), then you may have a symlink somewhere in your environment variables. So you may want to check for symlink.

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.

How to set JAVA_HOME in Windows

Three ways to set the JDK JAVA_HOME variable in Windows include:

  • allow the Java installer to do it;
  • use the environment variable editor; and
  • use the command line.

OpenJDK’s JAVA_HOME configuration tool

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:

  • add to PATH; or
  • set JAVA_HOME variable.

set JAVA_HOME OpenJDK

The OpenJDK JAVA_HOME setup tool greatly simplifies configuration.

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.

The JAVA_HOME environment variable editor

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:

  • Open the Windows System Properties Control Panel applet on any version of Windows.
  • Choose Advanced System settings.
  • Click on the Environment Variables button.
  • Click on the New button under System Variables.
  • Set JAVA_HOME as the environment variable name.
  • Set the location of the JDK installation as the environment variable Value.
  • Click OK and close the JAVA_HOME environment variable editor.

Windows 7 JAVA_HOME

How to use the JAVA_HOME environment variable editor in Windows 7.

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 setx JAVA_HOME command

The third way to configure the Windows JAVA_HOME environment variable is to use the command line and invoke the setx command as follows: 

@REM Configure JAVA_HOME in Windows 10 with setx
setx JAVA_HOME -m «C:_jdk12.0»
>> setx JAVA_HOME command completed successfully 

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.

How to echo JAVA_HOME in Windows

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 

JAVA_HOME Ubuntu

If you use a BASH shell, or if you have set JAVA_HOME in an Ubuntu environment and need to echo JAVA_HOME in Linux, place a single dollar sign before the environment variable: echo $JAVA_HOME.

How to get JAVA_HOME in Windows scripts

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%binjava.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 PATH setting in Windows

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.»

Java PATH variable

How to add the JDK bin directory to the Windows PATH.

The JAVA_HOME bin combination

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

How to set JRE_HOME in Windows

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.

Details
Written by  
Last Updated on 09 April 2020   |   Print  Email

Why do you need to setup environment variables in Java programming?

Well, in this article I talked about the JVM, JRE and JDK, which are the cornerstones of the Java programming language. You develop Java applications by using tools like editors, IDEs and servers. These tools need to use the Java compiler (javac) and Java launcher (java) to compile and run Java applications, but these tools don’t know where the JRE or JDK is.

So, by setting up the environment variables, you tell your tools that:

“Hey, you can find the compiler and launcher here and there”.

The first thing you need to do after installing the JDK is creating an environment variable named JAVA_HOME and then update the PATH variable.

  • JAVA_HOME: stores location of the JDK’s installation directory. When you install development tools, they will first check for the JAVA_HOME variable. If found, they will stick with it. If not, they may ask you to manually specify the location where JRE/JDK is installed.
     
  • PATH: stores paths of directories where the operating system will look, to launch the requested programs quickly. For Java development, you should update this environment variable by adding an entry to the bin directory under JDK’s installation directory.

For example, if the JDK is installed at C:Program FilesJavajdk1.8.0, then you need to set:

  • JAVA_HOME = C:Program FilesJavajdk1.8.0
  • PATH = PATH + C:Program FilesJavajdk1.8.0bin

Setting these environment variables on Windows is not difficult. Just go to Control Panel > System > Advanced system settings > Advanced > Environment Variables. You can see the whole steps to setup this stuff in the following article:

How to write, compile and run a hello world Java program for beginners

But that isn’t cool, because I’m about to show you how to do the same thing using command line prompt as shown below (Windows 7, 8 and 10):

setx JAVA_HOME "C:Program FilesJavajdk1.8.0"
setx PATH "%PATH%;%JAVA_HOME%bin";

The setx  command permanently updates the environment variables. To add/update system environment variables, you must use the -m switch and open the command prompt using Administrator privilege: Click Start, type cmd. When the cmd.exe icon appears, right click and select Run as administrator.

To add/update system environment variables:

setx -m JAVA_HOME "C:Program FilesJavajdk1.8.0"
setx -m PATH "%PATH%;%JAVA_HOME%bin";

I prefer setting the environment variables using this command-line alternative. It’s quick and easy instead of going through several dialogs like using the GUI.

To summary, here are some important points:

  • Always set JAVA_HOME when preparing development environment for Java.
  • JAVA_HOME points to the installation directory of JDK.
  • The PATH variable should contain an entry pointing to JAVA_HOMEbin.
  • Environment can be set either via the GUI or command line prompt.

I hope that you have learned something new today. You can also watch the following video for visual steps:

 

Related Tutorials:

  • How to set JAVA_HOME environment variable on Windows 10
  • How to check Java version
  • Understand 9 features of Java programming language
  • How to write, compile and run a hello world Java program for beginners

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Add comment


Download Article

The easiest ways to set the JAVA_HOME environment variable on any computer


Download Article

  • Windows
  • |

  • macOS
  • |

  • 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) or the Java Runtime Environment (JRE), 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.

Things You Should Know

  • Before you can set JAVA_HOME, you’ll need the full path to your JDK or JRE installation.
  • Once you set the JAVA_HOME environment variable, you can run the command echo $JAVA_HOME to see the new path.
  • To set the Java home and path on Linux or macOS permanently (even after a reboot), add the environment variables to your .bashrc or .zshrc file.
  1. Image titled Set Java Home Step 1

    1

    Find your Java installation directory. Assuming that you didn’t change the path for the JDK or JRE during installation is not changed, it should be in a directory under C:Program FilesJava. 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 FilesJava. The directory you’re looking for should have the name of the JDK version, such as C:Program FilesJavajdk-19.
    • If you installed the JRE instead of the JDK, you’ll have something like C:Program FilesJavajre1.8.0_351 instead.
    • 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.
  2. Image titled Set Java Home Step 2

    2

    Open your Advanced System Settings. Here’s how:

    • Press the Windows key on your keyboard and type advanced system.
    • Click View advanced system settings in the search results.

    Advertisement

  3. Image titled Set Java Home Step 3

    3

    Click the Environment Variables button. You’ll see it at the bottom-right corner of the System Properties window.

  4. Image titled Set Java Home Step 4

    4

    Click the New… button under «User variables.» 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 installations of the JDK and want to change JAVA_HOME to your new installation, select the current JAVA_HOME user variable and click Edit… instead.
  5. Image titled Set Java Home Step 5

    5

    Type JAVA_HOME as the «Variable name.»

    • If you’re editing the current JAVA_HOME path, you’ll already have JAVA_HOME here. So, you can skip this step.
  6. Image titled Set Java Home Step 6

    6

    Enter the full path to your JDK or JRE installation. For example, if the path is C:Program FilesJavajdk-19, 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.
  7. Image titled Set Java Home Step 7

    7

    Click OK. This takes you back to the Environment Variables window.

  8. Image titled Set Java Home Step 8

    8

    Select the Path user variable and click Edit. 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.
  9. Image titled Set Java Home Step 9

    9

    Append the path to your Java /bin directory to the end of the path. 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 JRE or JDK with bin at the end. For example, C:Program FilesJavajdk-19bin or C:Program FilesJavajre1.8.0_351bin.
    • Click OK.
  10. Image titled Set Java Home Step 10

    10

    Click OK on all subsequent windows. 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.
  11. Advertisement

  1. Image titled Set Java Home Step 11

    1

    Open a Terminal window. To open Terminal, search for Terminal in Spotlight. Or, you can open Finder, click the Go menu, select Utilities, and choose the Terminal app.

  2. Image titled Set Java Home Step 12

    2

    Type /usr/libexec/java_home and press Return. 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.
  3. Image titled Set Java Home Step 13

    3

    Copy the path and paste it somewhere handy. 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.

  4. Image titled Set Java Home Step 14

    4

    Open your .zshrc file in a text editor. 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.
  5. Image titled Set Java Home Step 15

    5

    Add these lines to the bottom of the file. 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-17.0.1.jdk/Contents/Home

      • Replace /Library/Java/JavaVirtualMachines/jdk-17.0.1.jdk/Contents/Home with the full path to the /Contents/Home directory of your Java installation if it’s different.
    • export PATH=$JAVA_HOME/bin:$PATH
    • Save the file and exit the text editor when you’re finished.
  6. Image titled Set Java Home Step 16

    6

    Type source .zshrc and press Return. 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).

  7. Image titled Set Java Home Step 17

    7

    Type echo $JAVA_HOME and press Return to confirm JAVA_HOME. You should now see the full path to JAVA_HOME.

    • If you had any other windows open that were attempting to find Java binaries, close and reopen them.
    • Shopping for PC accessories or office supplies? Check out our coupon site for Staples discounts or our coupon site for Office Depot.
  8. Advertisement

  1. Image titled Set Java Home Step 18

    1

    Open a terminal window. 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.
  2. Image titled Set Java Home Step 19

    2

    Find the location of your Java installation. 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-11-openjdk-arm64/bin/java. This is the directory you want.
  3. Image titled Set Java Home Step 20

    3

    Set the JAVA_HOME path. 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-11-openjdk-arm64" >> ~/.bashrc
    • echo "export PATH=$PATH:$JAVA_HOME/bin" >> ~/.bashrc
  4. Image titled Set Java Home Step 21

    4

    Type source .bashrc to apply the changes to the current terminal window. 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.
  5. 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 293,321 times.

Is this article up to date?

Во многих статьях в интернете, документации к инструментам для разработки на Java и в книгах зачастую упоминается JAVA_HOME. Что же такое JAVA_HOME?

JAVA_HOME это переменная окружения, указывающая на директорию с установленным JDK (Java Development Kit, комплект разработчика Java). JAVA_HOME это соглашение, используемое во многих программах из экосистемы Java.

Какие программы используют JAVA_HOME

  • Intellij IDEA, Eclipse, NetBeans
  • Apache Maven, Apache Ant, Gradle
  • Apache Tomcat
  • Jenkins

Некоторые игры, написанные на Java (например, Minecraft), тоже могут требовать установленной переменной JAVA_HOME.

Ошибки, связанные с JAVA_HOME

Если переменная окружения JAVA_HOME не определена, некоторые программы могут выдавать следующие ошибки:

  • Переменная среды java_home не определена
  • Cannot determine a valid Java Home
  • JAVA_HOME is set to an invalid directory
  • JAVA_HOME is not defined correctly
  • JAVA_HOME environment variable is not set
  • JAVA_HOME command not found
  • JAVA_HOME not found in your environment
  • JAVA_HOME does not point to the JDK

При появлении таких ошибок просто установите переменную JAVA_HOME

Как установить переменную окружения JAVA_HOME в Windows

Сперва вам нужно установить JDK или JRE.

  • Установите JDK, если вы занимаетесь разработкой программ на Java
  • Установите JRE, если вам нужно только запустить прикладную программу на Java

После установки JDK либо JRE запишите путь установки, он понадобится.

Теперь щёлкните правой кнопкой на «Мой компьютер» → «Свойства» → «Дополнительные параметры системы» → «Переменные среды…». В разделе «Системные переменные» нажмите кнопку «Создать…» и укажите следующие данные:

Имя переменной JAVA_HOME
Значение переменной Путь к директории JDK / JRE, например:
C:Javajdk-11.0.6

Сохраните изменения, кликнув «OK». Теперь выберите в списке переменную окружения Path и нажмите «Изменить…». В конце списка добавьте строчку со значением «%JAVA_HOME%bin«

Для проверки откройте консоль (Win+R, cmd) и укажите последовательно укажите две команды:

echo %JAVA_HOME%
java --version

Если вы правильно установили JDK/JRE и правильно установили переменные окружения, вы увидите вывод наподобие этого:

Это будет служить результатом того, что переменная JAVA_HOME установлена правильно и Java работает из командной строки.

Резюме

В данной статье мы рассказали вам, что являет собой переменная окружения JAVA_HOME, где она используется и как её корректно указать.

Понравилась статья? Поделить с друзьями:
  • Windows set environment variable from file
  • Windows set environment variable from command line
  • Windows servicing packages что это за папка
  • Windows serviceprofiles networkservice appdata local microsoft windows delivery optimization cache
  • Windows service volume shadow copy service