Linux check java home

How To Set Java Home Path In Linux?

Java is a popular programming language and framework in the IT industry. There are a lot of applications developed with Java. Java requires Java Development Kit to develop applications. Compiled java applications can run on systems those are installed Java Runtime Environment a.k.a JRE. We will look in this post on how to set and check JRE or JDK or Java Home Path.

Installation

There are two main different versions of JDK and JRE. The original vendor is Oracle which distributes and sets standards of Java. Second is an open version of JDK and JRE that are supported by Oracle. In this post, we will install the open version named as openjdk-9-jre-headless .

Installation

Check Java Status

We will look if java path already sets simple running java command which is a compiler for Java applications.

Check Java Status

Update Locate Database

This is auxiliary operation to use locate OpenJDK location we update locate database

Find JDK Location

We will look at where is JDK located and also get the JDK version. This operation can be used Oracle JDK too. Just the JDK directory name will be different.

Find JDK Location

Set Java Home

As we see there is a lot of output for JDK search we can see that the path of JDK is /usr/lib/jvm/java-9-openjdk-amd64 because it is located in usr lib. Now we will set PATH for Java

Set Java Home

Make Java Home Configuration Persistent

The previous step makes JAVA HOME available for subshells but if the system is restarted the path will be lost. So we need to make this path definition persistent. There are different methods to make persistent. We will look single and simple one. We will add path definition to the system-wide environment definition configuration. This operation requires root privileges.

An alternative method without the need for root privileges is adding Java home path definition to the normal user .bashrc file like below.

Make Java Home Configuration Persistent

Источник

Как найти JAVA_HOME

Узнайте, что существует несколько способов найти JAVA_HOME, в том числе независимый от платформы.

Автор: baeldung
Дата записи

1. введение

В этом кратком посте мы узнаем, как найти JAVA_HOME в Windows, Mac и Linux.

Как мы все знаем, JAVA_HOME – это переменная среды, которую мы обычно используем для поиска исполняемых файлов java, таких как java и javac .

2. Специфичные для Windows способы поиска JAVA_HOME

Если мы используем Windows в качестве операционной системы, сначала нам нужно открыть нашу командную строку ( cmd ) и ввести:

Если JAVA_HOME определен в нашей среде, то приведенная выше команда распечатает его.

Или мы могли бы попробовать:

Который покажет местоположение исполняемого файла java .

3. Специфичные для macOS и Linux способы поиска JAVA_HOME

Если мы используем macOS или Linux, мы можем открыть наш терминал и ввести:

Если JAVA_HOME определен в нашей среде, то приведенная выше команда распечатает его.

Или мы могли бы попробовать:

Что, вероятно, просто показывает нам /usr/bin/java.

Но на самом деле это не очень полезно, так как это символическая ссылка. Чтобы разгадать это, мы будем использовать dirname и readlink ;

В результате эта команда выводит используемую в данный момент папку java.

4. Использование Java для поиска JAVA_HOME

И, если мы можем запустить java сами, то у нас тоже есть почти независимый от платформы способ:

Выполнение этой команды выводит множество свойств, одним из которых является java.home.

Однако для его анализа нам все равно понадобится инструмент для конкретной платформы.

Для Linux и macOS , давайте использовать grep :

А для Windows давайте использовать findstr :

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

С помощью этого быстрого сообщения мы узнали, как найти JAVA_HOME в разных операционных системах.

Если они не сработали, возможно, мы неправильно установили переменную JAVA_HOME при установке Java.

Читайте также:  M1005 mfp scanner driver windows 10

Источник

How to set JAVA_HOME and PATH in Linux? Example

Like in the previous article, I explained a Maven issue (invalid target release: 1.7, 1.8) related to the Java version, which occurred even though the correct version of Java was installed on the machine, but JAVA_HOME was pointing to an older version.

Unfortunately, When you install Java on Linux or Windows, this environment variable is not set automatically. You need to do it yourself. Java developers like me always set mandatory environment variables like JAVA_HOME, PATH, and CLASSPATH on the login scripts executed by the shell when you log in to Linux like bash_profile.sh , but you can also set JAVA_HOME into /etc/profile for all users.

I’ll show you steps on how to find the location of Java and how to set up the JAVA_HOME in Linux in this article, and these steps should also work with any Linux or Java version like Ubuntu, RedHat, CentOS, SUSE, ArchLinux, Debian, Fedora, etc.

Though I strongly encourage every Java developer to learn Linux, it’s a really important skill and serves you for a long time. If you decide to improve your Linux skill this year, I suggest you take a look at these best online Linux courses, which are both short and sweet and also explains all important details.

1. Steps to set JAVA_HOME in Linux

1) The first step is to find the location where Java is installed on your Linux machine. To check that open putty and connect to your Linux server and type the following command

where options include:
-d32 use a 32-bit data model if available
-d64 use a 64-bit data model if available
-server to select the «server» VM

It means Java is installed and added to your PATH, so half of the job is done already. All you need to is find the location of JDK, which you can find either by printing PATH as follows

You can see that JDK is installed on «/usr/sun/jdk/v1.6.0_16-64bit».

2) Add the following line of your .bash_profile file if you want to set JAVA_HOME for yourself or /etc/profile if you want to set JAVA_HOME for all user

That’s it you are done. Though don’t forget to open another shell window by typing bash , csh , or ksh . The new environment variable will not be added to an existing shell, you need to open a new shell window.

Also, if you use bash shell then adding into

/.bash_profile makes sense, if you use csh (C shell) then add JAVA_HOME into

/.csh_profile, and similarly for ksh (K shell) add JAVA_HOME into

They are hidden files in your home directory in Linux, that’s why they had prefix dot (.) in their name. You can use «ls — alrt» command to see them.

Here is a sample /etc/profile file with JAVA_HOME and PATH variable defined for your reference:

By the way, if you don’t see Java installed on your machine, then download the Linux version of Java from Oracle’s website and install it.

Once you are done with installation just find the folder where JDK is installed and follow the steps given above to set JAVA_HOME for your Linux environment.

For applications, JAVA_HOME is generally referred to on the start script. It’s bad practice to refer to the hardcoded path of Java installation in scripts, you will never find Tomcat, Maven, Eclipse, NetBeans, or IntelliJ doing that because then when you update to a new Java version they won’t be able to use it until you change their start script.

Using JAVA_HOME makes it easy to switch to a different or new Java version. See these free Java development courses to learn more about the core concepts of Java in detail. It’s updated for Java 11 and also not very expensive, I just bouthbought11 a couple of days ago.

2. Why should you set JAVA_HOME in Linux

Even though many developers know about JAVA_HOME, they don’t set it in their environment due to various reasons. I strongly recommend you to set JAVA_HOME , PATH , and CLASSPATH for your development environment. Here are some reasons why you set JAVA_HOME in Linux

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 a new version and make sure your JAVA_HOME points to the new version of Java. This is the best benefit of using an environment variable or links.

Читайте также:  Загрузка windows с ssd или с hdd

2) The JAVA_HOME variable is short and concise instead of the full path to the JDK installation directory.

3) JAVA_HOME variable helps your program achieve platform independence like if your startup script uses JAVA_HOME, then it can run on Windows and UNIX without any modification; you just need to set JAVA_HOME on the respective operating system.

4) The JAVA_HOME is standard, which means other tools that need Java, like Maven, Eclipse can refer to this variable without having any knowledge of where Java is physically installed on your machine, which is obviously different in different user’s machines. JAVA_HOME allows everybody to access Java in a common and standard way.

I also suggest joining Java Fundamentals: The Java Language course on Pluaralsight to learn more about Java fundamentals like this one.

That’s all about how to set the JAVA_HOME environment variable in Linux. I have also touched base on why you should do it, which is probably more important. Many tools like Maven and IDEs like Eclipse and Netbeans use this variable to locate the JDK binaries installed on this machine, hence it’s better to set this up. If you face any problem while setting and using the JAVA_HOME environment variable, feel free to ask. I’ll be glad to help you out.

Источник

How to set JAVA_HOME for Java?

I’ve installed a version of Java. How can we set the $JAVA_HOME environment variable correctly?

3 Answers 3

You can set your JAVA_HOME in /etc/profile as Petronilla Escarabajo suggests. But the preferred location for JAVA_HOME or any system variable is /etc/environment .

Open /etc/environment in any text editor like nano or gedit and add the following line:

(java path could be different)

Use source to load the variables, by running this command:

Then check the variable, by running this command:

Update

Usually most linux systems source /etc/environment by default. If your system doesn’t do that add the following line to

/.bashrc (Thanks @pje)

/.bashrc so that it loads all my environment settings on startup. Working for me so far.

To set JAVA_HOME environment variable, do the following:

  1. Launch Terminal by pressing Ctrl + Alt + T on your keyboard.
  2. Enter the following command:
    $ gksudo gedit /etc/environment
  3. Depending on where you installed your Java, you will need to provide the full path. For this example, I installed Oracle JDK 7 in the /usr/lib/jvm/java-7-oracle directory.
    Scroll to the end of the file and enter the following:
    JAVA_HOME=/usr/lib/jvm/java-7-oracle
    export JAVA_HOME
  4. Save your file and exit gedit.
  5. Lastly, reload the system PATH with the following command:
    $ . /etc/environment

The above method will save you the hassle in having to run the commands every time you log in to your computer.

Источник

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.

java -version gives me:

  • java version «1.7.0_55»
  • OpenJDK Runtime Environment (rhel-2.4.7.1.el6_5-x86_64 u55-b13)
  • OpenJDK 64-Bit Server VM (build 24.51-b03, mixed mode)

When I am trying to build a Maven project , I am getting error:

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

Prepend sudo if logged in as not-privileged user, ie. sudo vim

  • logout and login again, reboot, or use source /etc/profile to apply changes immediately in your current shell
  • 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

    You have to remember that this file is only loaded with new login shells.. So after bash -l or a new gnome-session and that it doesn’t change with new Java versions.

    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 :

    Читайте также:  Readyboost windows 10 для чего

    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.

    Open terminal and type sudo gedit .bashrc

    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)

    ln -s latestJavaRelease /usr/java/default
    Where latestJavaRelease is the version that you want to use

    then export JAVA_HOME=/usr/java/default

    The answer is given previous posts is valid. But not one answer is complete with respect to:

    1. Changing the /etc/profile is not recommended simply because of the reason (as stated in /etc/profile):
    • It’s NOT a good idea to change this file unless you know what you are doing. It’s much better to create a custom.sh shell script in /etc/profile.d/ to make custom changes to your environment, as this will prevent the need for merging in future updates.*

    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:

    export JAVA_HOME=$(readlink -f /usr/bin/javac | sed «s:/bin/javac::»)

    #if making jre as java home

    export JAVA_HOME=$(readlink -f /usr/bin/java | sed «s:/bin/java::»)

    1. And remember to have #! /bin/bash on the custom.sh file

    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:

    This is a very simple script to solve the problem

    And for testing:

    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

    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.

    Step 1 — check the current java version by «echo $JAVA_HOME»

    Step 2 — vim /etc/profile

    Step 3 — At the end of file you will find export JAVA_HOME, we need to provide the new path here, make sure that it is not relative.

    Step 4 — Save and exit :wq

    Step 5 — «source /etc/profile/», this would execute the change

    Step 6 — Again do a echo $JAVA_HOME — change would have been reflected.

    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.

    either: source /etc/ or . /etc/

    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.

    Источник

    Оцените статью