Error java home is not defined correctly

I installed java and set the path environment and when I run echo $JAVA_HOME in the terminal I get the following output: /usr/lib/jvm/java-7-oracle/jre/bin/java I Also installed apache-maven and c...

I installed java and set the path environment and when I run echo $JAVA_HOME in the terminal I get the following output:

/usr/lib/jvm/java-7-oracle/jre/bin/java

I Also installed apache-maven and changed environment file and now it looks like this:

JAVA_HOME="/usr/lib/jvm/java-7-oracle/jre/bin/java"
M2_HOME=/usr/local/apache-maven/apache-maven-3.0.5
M2=$M2_HOME/bin
MAVEN_OPTS="-Xms256m -Xmx512m"
PATH=$M2:$PATH

But when I execute mvn --version I get a warning:

Error: JAVA_HOME is not defined correctly.
  We cannot execute /usr/lib/jvm/java-7-oracle/jre/bin/java/bin/java

Can not find out why it repeats in the end /bin/java/bin/java

Philip Mutua's user avatar

Philip Mutua

5,62811 gold badges37 silver badges77 bronze badges

asked Dec 5, 2014 at 15:40

user3127896's user avatar

user3127896user3127896

6,11314 gold badges39 silver badges62 bronze badges

2

Assuming you use bash shell and installed Java with the Oracle installer, you could add the following to your .bash_profile

export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$JAVA_HOME/jre/bin:$PATH

This would pick the correct JAVA_HOME as defined by the Oracle installer and will set it first in your $PATH making sure it is found.

Also, you don’t need to change it later when updating Java.

EDIT

As per the comments:

Making it persistent after a reboot

Just add those lines in the shell configuration file. (Assuming it’s bash)

Ex: .bashrc, .bash_profile or .profile (for ubuntu)

Using a custom Java installation

Set JAVA_HOME to the root folder of the custom Java installation path without the $().

Ex: JAVA_HOME=/opt/java/openjdk

answered Feb 24, 2015 at 1:48

rbento's user avatar

5

JAVA_HOME should be /usr/lib/jvm/java-7-oracle/jre/.

answered Dec 5, 2014 at 15:42

talex's user avatar

talextalex

17.7k3 gold badges28 silver badges62 bronze badges

1

We open a terminal and look for the location of java:

manuel@zonademanel:~ → whereis java

java: /usr/bin/java /etc/java /usr/bin/X11/java /usr/share/java
/usr/share/man/man1/java.1.gz

What we are looking for is /usr/bin/java continue on the command line to find the absolute path , as this is only a symbolic link.

manuel@zonademanel:~ → ls -lah /usr/bin/java

lrwxrwxrwx 1 root root 22 may 19 2015 /usr/bin/java ->
/etc/alternatives/java

manuel@zonademanel:~ → ls -lah /etc/alternatives/java

lrwxrwxrwx 1 root root 39 dic 7 11:52 /etc/alternatives/java ->
/usr/lib/jvm/java-8-oracle/jre/bin/java

I modified my /etc/environment file with the following values

PATH=»/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/usr/lib/jvm/java-8-oracle/jre/bin»
JAVA_HOME=»/usr/lib/jvm/java-8-oracle/jre«

If I do not want to relogin I can reload the changes with:

source /etc/environment 

​​And run mvn -version correctly

manuel@zonademanel:~ → mvn -version

Apache Maven 3.0.5
Maven home: /usr/share/maven
Java version: 1.8.0_77, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-8-oracle/jre
Default locale: es_MX, platform encoding: UTF-8
OS name: «linux», version: «3.16.0-70-generic», arch: «amd64», family: «unix»

borjab's user avatar

borjab

10.8k6 gold badges69 silver badges95 bronze badges

answered Apr 14, 2016 at 16:15

Juan Manuel Garcia Carmona's user avatar

0

$JAVA_HOME should be the directory where java was installed, not one of its parts:

export JAVA_HOME=/usr/lib/jvm/java-7-oracle

answered Dec 5, 2014 at 15:42

Mureinik's user avatar

MureinikMureinik

290k52 gold badges300 silver badges337 bronze badges

You might get this error due to couple of reasons. To fix this quickly please follow below steps,

First find the java location. To get a list of your installed Java platforms, run the following command from the terminal:

$ sudo update-alternatives --config java

Now set JAVA_HOME and PATH,

$ export JAVA_HOME=<java_home>

$ export PATH=$JAVA_HOME/jre/bin:$PATH

Create the symlink

$ sudo ln -s <java_home>/jre <java_symlink_path>

When we take your case as a example :

$ sudo ln -s /usr/lib/jvm/java-7-oracle/jre /usr/lib/jvm/java-7-oracle/jre/bin/java

Above command will create the symlink location where the system is trying to find in your issue.

Finally do the

$ mvn --version

answered May 27, 2016 at 9:28

tk_'s user avatar

tk_tk_

15.8k8 gold badges80 silver badges89 bronze badges

1

You should set as it is export JAVA_HOME=/usr/java/jdk1.8.0_31 and run with sudo it will execute as shown below.

Example

sudo mvn -v

OUTPUT

Apache Maven 3.6.0
Maven home: /usr/share/maven
Java version: 11.0.10, vendor: Ubuntu, runtime: /usr/lib/jvm/java-11-openjdk-amd64
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "5.4.0-70-generic", arch: "amd64", family: "unix"

Philip Mutua's user avatar

Philip Mutua

5,62811 gold badges37 silver badges77 bronze badges

answered Mar 17, 2015 at 13:07

rohit sawant's user avatar

2

Firstly, in a development mode, you should use JDK instead of the JRE.
Secondly, the JAVA_HOME is where you install Java and where all the others frameworks will search for what they need (JRE,javac,…)

So if you set

JAVA_HOME=/usr/lib/jvm/java-7-oracle/jre/bin/java

when you run a «mvn» command, Maven will try to access to the java by adding /bin/java, thinking that the JAVA_HOME is in the root directory of Java installation.

But setting

JAVA_HOME=/usr/lib/jvm/java-7-oracle/

Maven will access add bin/java then it will work just fine.

answered Sep 18, 2015 at 19:37

Jad B.'s user avatar

Jad B.Jad B.

1,39614 silver badges14 bronze badges

This solution work for me…
just type
export PATH=$JAVA_HOME/jre/bin:$PATH in the terminal
then run mvn -version
it will show the same error but with a log like this

which: no javac in (/jre/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/puppetlabs/bin)
Warning: JAVA_HOME environment variable is not set.
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T22:59:23+05:30)
Maven home: /opt/apache-maven-3.2.5
Java version: 1.8.0_171, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.el7_5.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-693.el7.x86_64", arch: "amd64", family: "unix"

now copy the Java home path i.e. /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.el7_5.x86_64/jre in my case.

now type,

export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.el7_5.x86_64/jre

and the error gets resolve.
NOTE: paste your own path which is shown by your machine in mvn log at export JAVA_HOME.

answered Jul 8, 2018 at 5:34

Mohit Garg's user avatar

You must take the whole directory where java is installed, in my case:

export JAVA_HOME=/usr/java/jdk1.8.0_31

Rizier123's user avatar

Rizier123

58.3k16 gold badges96 silver badges153 bronze badges

answered Feb 24, 2015 at 0:18

ascoder's user avatar

ascoderascoder

5753 silver badges14 bronze badges

It happens because of the reason mentioned below :

If you see the mvn script: The code fails here —

Steps for debugging and fixing:

Step 1: Open the mvn script /Users/Username/apache-maven-3.0.5/bin/mvn
(Open with the less command like: less /Users/Username/apache-maven-3.0.5/bin/mvn)

Step 2: Find out the below code in the script:

  if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java"
    fi
  else
    JAVACMD="`which java`"
  fi
fi

if [ ! -x "$JAVACMD" ] ; then
  echo "Error: JAVA_HOME is not defined correctly."
  echo "  We cannot execute $JAVACMD"
  exit 1
fi

Step3: It is happening because JAVACMD variable was not set. So it displays the error.

Note: To Fix it

export JAVACMD=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/bin/java

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/

Key: If you want it to be permanent
open emacs .profile

post the commands
and press Ctrl-x Ctrl-c ( save-buffers-kill-terminal ).

answered Jun 15, 2017 at 9:48

Shubham Verma's user avatar

Shubham VermaShubham Verma

9671 gold badge10 silver badges13 bronze badges

If you are using mac-OS , export JAVA_HOME=/usr/libexec/java_home need to be changed to export JAVA_HOME=$(/usr/libexec/java_home) .
Steps to do this :

 $ vim .bash_profile

 export JAVA_HOME=$(/usr/libexec/java_home)

 $ source .bash_profile

where /usr/libexec/java_home is the path of your jvm

answered Jul 26, 2017 at 4:36

ishanbakshi's user avatar

ishanbakshiishanbakshi

1,8852 gold badges19 silver badges37 bronze badges

Use these two commands (for Java 8):

sudo update-java-alternatives --set java-8-oracle
java -XshowSettings 2>&1 | grep -e 'java.home' | awk '{print "JAVA_HOME="$3}' | sed "s//jre//g" >> /etc/environment

answered Mar 25, 2018 at 18:11

Xdg's user avatar

XdgXdg

1,6752 gold badges25 silver badges42 bronze badges

In my case, the problem was in vscode.

I use windows and installed Ubuntu on my computer, so vscode terminal uses the Ubuntu. I just go to settings.json and change to cmd.exe again

answered Aug 29, 2019 at 19:42

Pedrojonassm's user avatar

I had this same issue but with open jdk and none of the answers here helped. The trouble was that the mvn script was appending /bin/java at the end of JAVA home while trying to run java commands.

The solution for me was to manually edit the /usr/local/apache-maven/apache-maven-3.3.9/bin/mvn script (your own script might be installed differently; just run which mvn) and change

   if [ -z "$JAVACMD" ] ; then
  if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else
      JAVACMD="$JAVA_HOME/bin/java" 
    fi
  else
    JAVACMD="`which java`"
  fi
 fi

To

if [ -n "$JAVA_HOME"  ] ; then
    if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
      # IBM's JDK on AIX uses strange locations for the executables
      JAVACMD="$JAVA_HOME/jre/sh/java"
    else 
      JAVACMD="$JAVA_HOME"
    fi
  else
    JAVACMD="`which java`"
  fi
fi

answered Oct 22, 2020 at 20:07

larisoft's user avatar

larisoftlarisoft

1912 silver badges5 bronze badges

add in .bash_profile

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export PATH=$JAVA_HOME/jre/bin:$PATH

and then

source .bash_profile

answered Feb 18, 2022 at 11:58

Flavio Troia's user avatar

Flavio TroiaFlavio Troia

2,3161 gold badge25 silver badges26 bronze badges

I had similar issue and it was not getting resolved even after editing and sourcing the .bash_profile, .bashrc file. I got it resolved by editing the maven.sh file directly.

export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-11.0.16.0.8-1.amzn2.0.1.x86_64
export M2_HOME=/opt/maven
export M2=/opt/maven/bin
export PATH=$PATH:$HOME/bin:$JAVA_HOME:$M2HOME:$M2

and then sourcing the file

source /etc/profile.d/maven.sh

For those who didnt get they issue resolved with other answers, give this a try as well.

answered Jan 3 at 10:35

eccentricCoder's user avatar

eccentricCodereccentricCoder

8561 gold badge12 silver badges35 bronze badges

JAVA_HOME должен указывать на JDK, а не на JRE

1. Вступление

В этом руководстве мы поговорим об исключении, которое Maven выдает при неправильной настройке:JAVA_HOME should point to a JDK, not a JRE.

Maven — мощный инструмент для создания кода. Мы посмотрим изнутри, чтобы понять, почему происходит эта ошибка, и посмотрим, как ее устранить.

2. ПроблемаJAVA_HOME

После установки Maven выполняетсяwe have to set the JAVA_HOME environment variable, so the tool knows where to find the JDK commands. Цели Maven запускают соответствующие команды Java в исходном коде проекта.

Например, наиболее распространенным сценарием является компиляция кода путем выполнения командыjavac.

ЕслиJAVA_HOME is not pointing to a valid JDK installation, Maven выдает ошибку при каждом выполнении:

mvn -version

# Output... 
The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK, not a JRE

3. JDK или JRE

Как Maven проверяет путьJAVA_HOME?

Перед запуском любых целей введитеMaven checks for the existence of the java command по пути, указанномуJAVA_HOME, или запросив у ОС установку JDK по умолчанию. If the executable is not found, Maven terminates with the error.

Вот проверка исполняемого файлаmvn для Linux (Apache Maven v3.5.4):

if [ -z "$JAVA_HOME" ] ; then
    JAVACMD=`which java`
else
    JAVACMD="$JAVA_HOME/bin/java"
fi
 
if [ ! -x "$JAVACMD" ] ; then
    echo "The 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
    exit 1
fi

Эта проверка на первый взгляд может показаться разумной, но мы должны учитывать, чтоboth JDK and JRE have a bin folder and both contain an executable java file.

Следовательно, этоpossible to configure JAVA_HOME to point to a JRE installation, hiding this particular error and causing problems at a later stage.. В то время как основная цель JRE — запуск кода Java,the JDK can also compile and debug among other important differences.

По этой причине командаmvn compile не сработает, как мы увидим в следующем подразделе.

3.1. Ошибка компиляции из-за JRE вместо JDK

Как обычно с настройками по умолчанию, они очень полезны, если у нас есть «стандартная» конфигурация.

Например, если мы устанавливаем Java 11 в системе Ubuntu 18.04 и не устанавливаем переменную средыJAVA_HOME, Maven все равно с радостью найдет наш JDK и будет использовать его для различных целей, включая компиляцию.

Но если нам удалось настроить нестандартную конфигурацию (не говоря уже о том, чтобы навести беспорядок) в нашей системе, полезности Maven уже недостаточно. Это может даже вводить в заблуждение.

Предположим, у нас есть следующая конфигурация в Ubuntu 18.04:

  • JDK 11

  • JRE 8

  • JAVA_HOME — путь к установке JRE 8

Если мы сделаем нашу основную проверку:

Мы получим такой значимый результат:

Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-24T18:41:47Z)
Maven home: /opt/apache-maven-3.6.0
Java version: 1.8.0_191, vendor: Oracle Corporation, runtime: /usr/lib/jvm/java-8-openjdk-amd64/jre
Default locale: en, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-42-generic", arch: "amd64", family: "unix"

Посмотрим, что произойдет, если мы попытаемся скомпилировать проект:

Теперь мы получаем ошибку:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project my-app: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

3.2. Исправление ошибки компиляции на уровне проекта

Как и во многих других случаях с Maven, рекомендуется установить значимые общесистемные настройки — в этом случае мы изменим значение переменнойJAVA_HOME, как описано в разделе 5, чтобы указать на JDK вместо JRE.

Однако, если по какой-либо причине мы не можем установить значения по умолчанию,we can still override the settings on the project level. Посмотрим, как это сделать.

Сначала мы откроемpom.xml нашего проекта, перейдем в разделbuild / pluginManagement / plugins и посмотрим на запись дляmaven-compiler-plugin:


    maven-compiler-plugin
    3.7.0

Затем мы добавим в него конфигурацию, чтобы он использовал настраиваемый исполняемый файл, и пропустили поискjavac в каталогеJAVA_HOME/bin:


    maven-compiler-plugin
    3.7.0
    
        true
        /usr/lib/jvm/java-11-openjdk-amd64/bin/javac
    

В системах Unix этот исполняемый файл должен быть скриптом с соответствующими разрешениями. В системах Windows это должен быть файл.exe.

Далее попробуем снова скомпилировать проект:

Теперь сборка — включая фазу компиляции сmaven-compiler-plugin — прошла успешно.

4. Проверка конфигурацииJAVA_HOME

check if JAVA_HOME points to an actual JDK.  довольно просто. Мы можем либо распечатать его содержимое в терминале, либо запустить одну из следующих команд оболочки:

4.1. ПроверкаJAVA_HOME в Linux

Просто откройте терминал и введите:

> $JAVA_HOME/bin/javac -version

ЕслиJAVA_HOME указывает на JDK, результат должен выглядеть так:

ЕслиJAVA_HOME не указывает на JDK, ОС выдает сообщение об ошибке:

> bash: /bin/javac: No such file or directory

4.2. ПроверкаJAVA_HOME в Windows

Откройте командную строку и введите:

%JAVA_HOME%binjavac -version

ЕслиJAVA_HOME указывает на JDK, результат должен выглядеть так:

ЕслиJAVA_HOME не указывает на JDK, ОС выдает сообщение об ошибке:

> The system cannot find the path specified.

5. Как решить проблему

Прежде всего, нам нужно знать, где найти наш JDK:

  • Если мы установили наш дистрибутив JDK с помощью установщика пакетов, мы сможем найти путь с помощью утилиты поиска ОС

  • Если дистрибутив был переносным, давайте проверим папку, в которую мы его извлекли.

6. Заключение

В этом кратком руководстве мы обсудили ошибку «JAVA_HOME should point to a JDK not a JRE” Maven и изучили ее первопричину.

Наконец, мы обсудили, как проверить вашу переменную средыJAVA_HOME и как убедиться, что она указывает на JDK.

1. Introduction

In this tutorial, we’re going to talk about an exception that Maven throws when misconfigured: JAVA_HOME should point to a JDK, not a JRE.

Maven is a powerful tool for building code. We’ll look under the hood to understand why this error happens and will see how to solve it.

2. The JAVA_HOME Problem

After installing Maven, we have to set the JAVA_HOME environment variable, so the tool knows where to find the JDK commands to execute. Maven goals run the appropriate Java commands against the project’s source code.

For example, the most common scenario is to compile the code by executing the javac command.

If JAVA_HOME is not pointing to a valid JDK installation, Maven will throw an error at every execution:

mvn -version

# Output... 
The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK, not a JRE

3. JDK or JRE

How does Maven verify the JAVA_HOME path?

Before running any goals, Maven checks for the existence of the java command in the path specified by JAVA_HOME or by asking the OS for a default JDK installation. If the executable is not found, Maven terminates with the error.

Here is the mvn executable check for Linux (Apache Maven v3.5.4):

if [ -z "$JAVA_HOME" ] ; then
    JAVACMD=`which java`
else
    JAVACMD="$JAVA_HOME/bin/java"
fi
 
if [ ! -x "$JAVACMD" ] ; then
    echo "The 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
    exit 1
fi

This check may seem reasonable at first glance, but we have to consider that both JDK and JRE have a bin folder and both contain an executable java file.

Therefore, it’s possible to configure JAVA_HOME to point to a JRE installation, hiding this particular error and causing problems at a later stage. While the JRE’s main purpose is to run Java code, the JDK can also compile and debug among other important differences.

For this reason, an mvn compile command would fail – as we’ll see in the next subsection.

3.1. Compilation Failure Because of JRE Instead of JDK

As usual with default settings, they’re very helpful if we have a “standard” configuration.

For example, if we install Java 11 on an Ubuntu 18.04 system and don’t set the JAVA_HOME environment variable, Maven will still happily find our JDK and use it for the different goals, including compiling.

But if we’ve managed to set up a non-standard configuration (let alone made a mess) on our system, Maven’s helpfulness doesn’t suffice anymore. It can be even misleading.

Let’s assume we have the following configuration on Ubuntu 18.04:

  • JDK 11
  • JRE 8
  • JAVA_HOME set to the path of the JRE 8 installation

If we do our basic check:

mvn --version

We’ll get a meaningful output like this:

Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-24T18:41:47Z)
Maven home: /opt/apache-maven-3.6.0
Java version: 1.8.0_191, vendor: Oracle Corporation, runtime: /usr/lib/jvm/java-8-openjdk-amd64/jre
Default locale: en, platform encoding: UTF-8
OS name: "linux", version: "4.15.0-42-generic", arch: "amd64", family: "unix"

Let’s see what happens if we try to compile a project:

mvn clean compile

Now, we get an error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.7.0:compile (default-compile) on project my-app: Compilation failure
[ERROR] No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

3.2. Fixing the Compilation Error on the Project Level

As in many other cases with Maven, it’s recommended to set up meaningful system-wide settings – in this case, we’ll change the value of the JAVA_HOME variable as described in section 5 to point to the JDK instead of the JRE.

However, if we can’t set up defaults for whatever reason, we can still override the settings on the project level. Let’s see how to do that.

First, we’ll open the pom.xml of our project, go to the section build / pluginManagement / plugins and have a look at the entry for the maven-compiler-plugin:

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
</plugin>

Then, we’ll add a configuration to it so that it uses a custom executable and skip searching for javac in the JAVA_HOME/bin directory:

<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.7.0</version>
    <configuration>
        <fork>true</fork>
        <executable>/usr/lib/jvm/java-11-openjdk-amd64/bin/javac</executable>
    </configuration>
</plugin>

On Unix systems, this executable should be a script with adequate permission. On Windows systems, it should be an .exe file.

Next, we’ll try to compile the project again:

mvn clean compile

Now, the build – including the compile phase with the maven-compiler-plugin – is successful.

4. Checking the JAVA_HOME Configuration

It’s pretty simple to check if JAVA_HOME points to an actual JDK. We can either print its content in a terminal, or we can run one of the following shell commands:

4.1. Checking JAVA_HOME on Linux

Just open a terminal and type:

> $JAVA_HOME/bin/javac -version

If JAVA_HOME points to a JDK, the output should look like:

> javac 1.X.0_XX

If JAVA_HOME doesn’t point to a JDK, the OS will throw an error message:

> bash: /bin/javac: No such file or directory

4.2. Checking JAVA_HOME on Windows

Open a command prompt and type:

%JAVA_HOME%binjavac -version

If JAVA_HOME points to a JDK, the output should look like:

> javac 1.X.0_XX

If JAVA_HOME doesn’t point to a JDK, the OS will throw an error message:

> The system cannot find the path specified.

5. How to Solve the Issue

First of all, we need to know where to find our JDK:

  • If we installed our JDK distribution using a package installer, we should be able to find the path using the OS search utility
  • If the distribution was a portable one, let’s check the folder where we extracted it

Once we know the path to the JDK, we can set our JAVA_HOME environment variable, using the appropriate results for our particular OS.

6. Conclusion

In this brief tutorial, we’ve discussed the “JAVA_HOME should point to a JDK not a JRE” Maven error and examined its root cause.

Finally, we discussed how to check your JAVA_HOME environment variable, and how to make sure it points to a JDK.

Во многих статьях в интернете, документации к инструментам для разработки на 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, где она используется и как её корректно указать.

How to fix JAVA_HOME errors

There’s nothing worse than installing your favorite Java-based application — such as Minecraft, Maven, Jenkins or Apache Pig — only to run into a JAVA_HOME is set to an invalid directory or a JAVA_HOME is not defined correctly error as soon as you boot up the program.

Well, there’s no need to fret. Here’s how to fix the most common JAVA_HOME errors.

How to fix JAVA_HOME not found errors

It’s worth noting that there aren’t standardized JAVA_HOME error messages that people will encounter. There are many different ways that a given JAVA_HOME error might be logged.

For example, one of the most common JAVA_HOME configuration problems arises from the fact that the environment variable has never actually been set up. Such a scenario tends to trigger the following error messages:

  • Error: JAVA_HOME not found in your environment
  • Error: JAVA_HOME not set
  • Error: JAVA_HOME is not set currently
  • Error: JAVA_HOME is not set
  • Error: Java installation exists but JAVA_HOME has not been set
  • Error: JAVA_HOME cannot be determined from the registry

How do you fix the JAVA_HOME not found problem?

Well, you fix this by in the Windows environment variable editor where you can actually add a new system variable. If you know your way around the Windows operating system, you should be able to add the JAVA_HOME environment variable to your configuration and have it point to the installation root of your JDK within minutes. The Windows 10 setting looks like this:

JAVA_HOME not found

Fix JAVA_HOME not found errors

As mentioned above, the JAVA_HOME variable must point to the installation root of a JDK, which means a JDK must actually be installed. If one isn’t, then you better hop to it and get that done.

The JAVA_HOME is set to an invalid directory fix

The next most common JAVA_HOME error message is JAVA_HOME is set to an invalid directory. The error message is delightfully helpful, because it tells you in no uncertain terms the environment variable does in fact exist. And, it also tells you it’s not pointing to the right place, which is helpful as well. All you need to do to fix this error is edit the JAVA_HOME variable and point it to the correct directory.

The JAVA_HOME environment variable must point to the root of the installation folder of a JDK. It cannot point to a sub-directory of the JDK, and it cannot point to a parent directory that contains the JDK. It must point directly at the JDK installation directory itself. If you encounter the JAVA_HOME invalid directory error, make sure the name of the installation folder and the value of the variable match.

An easy way to see the actual value associated with the JAVA_HOME variable is to simply echo its value on the command line. In Windows, write:

>/echo %JAVA_HOME%
C:/_JDK13.0

On an Ubuntu, Mac or Linux machine, the command uses a dollar sign instead of percentages:

:-$ echo $JAVA_HOME
/usr/lib/jvm/java-13-oracle

Find JAVA_HOME Ubuntu

How to find JAVA_HOME in Mac or Ubuntu Linux computers.

Steer clear of the JDK bin directory

One very common developer mistake that leads to the JAVA_HOME is set to an invalid directory error is pointing JAVA_HOME to the bin sub-directory of the JDK installation. That’s the directory you use to configure the Windows PATH, but it is wrong, wrong, wrong when you set JAVA_HOME. If you point JAVA_HOME at the bin directory, you’ll need to fix that.

This misconfiguration also manifests itself with the following error messages:

  • JAVA_HOME is set to an invalid directory
  • Java installation exists but JAVA_HOME has been set incorrectly
  • JAVA_HOME is not defined correctly
  • JAVA_HOME does not point to the JDK

Other things that might trigger this error include spelling mistakes or case sensitivity errors. If the JAVA_HOME variable is set as java_home, JAVAHOME or Java_Home, a Unix, Linux or Ubuntu script will have a hard time finding it. The same thing goes for the value attached to the JAVA_HOME variable.

The JAVA_HOME does not point to the JDK error

One of the most frustrating JAVA_HOME errors is JAVA_HOME does not point to the JDK.

Here’s a little bit of background on this one.

When you download a JDK distribution, some vendors include a Java Runtime Environment (JRE) as well. And when the JAVA_HOME environment variable gets set, some people point it at the JRE installation folder and not the JDK installation folder. When this happens, we see errors such as:

  • JAVA_HOME does not point to a JDK
  • JAVA_HOME points to a JRE not a JDK
  • JAVA_HOME must point to a JDK not a JRE
  • JAVA_HOME points to a JRE

To fix this issue,  see if you have both a JRE and JDK installed locally. If you do, ensure that the JAVA_HOME variable is not pointing at the JRE.

JAVA_HOME and PATH confusion

After you’ve downloaded and installed the JDK, sometimes another problem can plague developers. If you already have programs that installed their own version of the JDK, those programs could have added a reference to that specific JDK in the Linux or Windows PATH setting. Some programs will run Java using the program’s availability through the PATH first, and JAVA_HOME second. If another program has installed a JRE and put that JRE’s bin directory on the PATH, your JAVA_HOME efforts may all be for naught.

However, you can address this issue. First, check the Ubuntu or Windows PATH variable and look to see if any other JRE or JDK directory has been added to it. You might be surprised to find out that IBM or Oracle has at some prior time performed an install without your knowledge. If that’s the case, remove the reference to it from the PATH, add your own JDK’s bin directory in there, and restart any open command windows. Hopefully that will solve the issue.

Of course, there is never any end to the configurations or settings that can trigger JAVA_HOME errors. If you’ve found any creative solutions not mentioned here, please add your expert insights to the comments.

Operating System Windows 10
java version "1.8.0_161" - jre

C:Usersadmin>echo %JAVA_HOME%
C:Program FilesJavajdk1.8.0_91;

Error (Command line)
C:Usersadmin>mvn -version
The JAVA_HOME environment variable is not defined correctly
This environment variable is needed to run this program
NB: JAVA_HOME should point to a JDK not a JRE

demouser123's user avatar

demouser123

3,5405 gold badges26 silver badges40 bronze badges

asked Apr 19, 2018 at 13:41

Sudeept's user avatar

2

Get rid of the trailing backslash and especially the trailing semi-colon:

C:Program FilesJavajdk1.8.0_91

By the way, you can display the current setting with the shorthand of typing «set» at a command prompt followed by the minimal number of characters needed, i.e. on my system:

set j
JAVA_HOME=C:Program FilesJavajdk1.8.0_144

answered Apr 19, 2018 at 14:41

Bill Hileman's user avatar

2

I had the same issue.
Please remove the backslash(») and semicolon.

For windows 10, here are the steps:

  1. Open Environment Variables
  2. Select ‘JAVA_HOME‘ under system variables
  3. Click Edit
  4. Remove the ; from path under the ‘variable name’.
  5. Click ‘OK’

Done.
RUN the mvn -version command and it shall work.

Prome's user avatar

Prome

1,0078 silver badges24 bronze badges

answered Jul 2, 2020 at 9:41

Rishi Bharadwaj's user avatar

Понравилась статья? Поделить с друзьями:
  • Error java home environment variable is not set
  • Error java error release version 5 not supported как исправить
  • Error java error release version 5 not supported maven
  • Error java error release version 5 not supported intellij
  • Error java compilation failed internal java compiler error