Как прописать java home mac os

java_home and JAVA_HOME on macOS

Ever wondered where Java stuff lives on your Apple Mac? Ever had to find how to set your environment to work with a specific version of Java? Ever manually set the JAVA_HOME environment variable to get something working?

If so, this note may help.

macOS is the operating system that runs on Apple Mac hardware. I have used Java on these machines for many years. A lot of things have changed in that time: Apple used to bundle Java; Oracle bought Sun; Apple stopped bundling Java … macOS was previously known as Mac OS X and later OS X. Oracle still use the old OS X branding.

I have just installed the latest Java upgrade and decided to try to understand how to work with the different versions of Java on macOS. Then I decide to write about it!

I read JDK 8 Installation for OS X from the Java Platform SE Installation Guide some time ago. But I failed to appreciate the java_home command.

This Note for Geeks:

  • describes how to use java_home to set the JAVA_HOME environment variable
  • describes how the java_home —exec can be used to execute Java commands for a specific JDK version independent of JAVA_HOME
  • describes a bash profile to enable interactive setting of the JDK version
  • shares some observations on Java symbolic links on macOS
  • is relevant to Java on macOS and versions of OS X since 2012

Earlier versions of Java SE have serious security risks corrected in later versions.

That creates a serious security vulnerability. Even if you installed the most recent version of Java SE, the personal information on your computer may be at risk because earlier, less secure versions could still be executed.

To fix this problem, visit http://java.com/uninstall, where instructions on how to uninstall older versions of Java SE are provided.

java_home

/usr/libexec/java_home is the simplest maintainable way of setting JAVA_HOME on macOS.

You can use java_home to:

  • Find all installed JDKs
  • Get value for JAVA_HOME for a specific JDK version
  • Get the value of JAVA_HOME for the default JDK version
  • Execute specific versions of Java commands

Finding all installed JDKs

NOTE: I will consider uninstalling the 1.6 versions to remove any associate security vulnerabilities

Getting values for JAVA_HOME for specific JDK versions

Getting the value of JAVA_HOME for the default JDK version

Executing specific versions of Java commands, such as java

java_home is the best way on macOS to execute a Java command . jdk/Contents/Home/bin/ for a specific version of the JDK. And it is independent of the setting of JAVA_HOME .

  • Executing the default version of a java
  • Executing a specific version of java command

man java_home

NOTE: The use of $JAVA_HOME in the man page is misleading because:

java_home can be used to return a value that can be used to set $JAVA_HOME

The —exec command can be used to execute a command . /Home/bin/ as if it was $JAVA_HOME/bin/ without changing or using $JAVA_HOME .

JAVA_HOME

The JAVA_HOME environment variable contains the home location of an installed JDK.

/usr/libexec/java_home is the simplest maintainable way of setting JAVA_HOME .

  • Set JAVA_HOME to JDK version 1.7
  • Set JAVA_HOME to the default JDK
  • Check JAVA_HOME
  • Check the actual java version

Independence of java_home —exec from $JAVA_HOME

java_home —exec can be used to execute Java commands independent of the setting of $JAVA_HOME .

The following examples demonstrate executing three different versions of the java command without changing $JAVA_HOME :

  • version using $JAVA_HOME
  • specific version using java_home —exec java -v 1.7
  • default version using java_home —exec java

How I use java_home to set JAVA_HOME

This setup is for bash, the Bourne Again Shell on macOS. There are similar variations for other shells.

Set environment variables in .bash_profile

This profile creates aliases to enable interactive setting of the JDK version and sets JAVA_HOME to the default JDK.

Use the aliases to interactively set JAVA_HOME

Set JAVA_HOME to v 1.7

Check java version

Set JAVA_HOME to v 1.8

Check java version

I have been lost a few times trying to follow the symbolic linking of Java versions in and out of /System/Library/Frameworks/JavaVM.framework/Versions/ and /Library/Java/JavaVirtualMachines/ .

The following are what seem to matter.

Which java

The java command is symlinked deep in the JavaVM.framework

The java_home command is symlinked deep in the JavaVM.framework

Assumption

The Java commands in /usr/bin/ appear to execute the corresponding Java commands for JAVA_HOME .

Each Java command /usr/bin/ executes $JAVA_HOME/bin/

Источник

Как установить переменную среды $JAVA_HOME в mac OS

Для оболочки zsh экспортируйте $JAVA_HOME в `

/.zshrc`; Для оболочки bash экспортируйте $JAVA_HOME в `

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

В этой статье показано, как установить переменную среды $JAVA_HOME в старых версиях Mac OS X и последней версии mac OS 11.

  1. история выпуска mac OS
  2. Что такое/usr/libexec/java_home
  3. $$JAVA_HOME и mac OS 11 Биг Сур
  4. $JAVA_HOME и Mac OS X 10.5 Леопард
  5. $JAVA_HOME и более старые версии Mac OS X
  6. Переключение между различными версиями JDK

Решение Шаги по установке переменной среды $JAVA_HOME в mac OS.

  1. Узнайте свою версию macOS.
  2. Узнайте, какую оболочку вы используете, bash или zsh?
  3. Для оболочки zsh экспортируйте $JAVA_HOME в

/.zshrc .
Для оболочки bash экспортируйте $JAVA_HOME в

/.bashrc .

  • Протестируйте с помощью echo $JAVA_HOME .
  • Сделано.
  • Связанный Прочтите это – Как установить Java JDK на macOS

    1. история выпуска mac OS, bash или zsh?

    1.1 Просмотрите историю выпуска macOS, источник Википедия – macOS .

    1. Публичная бета-версия Mac OS X
    2. Mac OS X 10.0 для Mac OS X 10.0 (Гепард)
    3. Mac OS X 10.1 (Пума)
    4. Mac OS X 10.2 Ягуар
    5. Mac OS X 10.3 Пантера
    6. Mac OS X 10.4 Тигр
    7. Mac OS X 10.5 Леопард
    8. Mac OS X 10.6 Снежный Барс
    9. Mac OS X 10.7 Лев
    10. OS X 10.8 Горный лев
    11. ОПЕРАЦИОННАЯ СИСТЕМА X 10.9 Индивидуалисты
    12. ОПЕРАЦИОННАЯ СИСТЕМА X 10.10 Йосемити
    13. OS X 10.11 капитан
    14. macOS 10.12 Sierra
    15. macOS 10.13 Высокая Сьерра
    16. macOS 10.14 Мохаве
    17. macOS 10.15 Каталина (zsh)
    18. macOS 11 Биг Сур (zsh)

    1.2 баш или zsh? В macOS 10.15 Catalina и более поздних версиях оболочка терминала по умолчанию переключается с втулки (Борн – снова снаряд) к зш (Оболочка Z).

      Для оболочки bash мы можем поместить переменные среды в

    /.bashrc .
    Для оболочки zsh мы можем поместить переменные среды в

    Мы можем распечатать переменную среды $SHELL , чтобы определить текущую используемую вами оболочку.

    2. Что такое/usr/libexec/java_home

    2.1 В Mac OS X 10.5 или более поздней версии мы можем использовать /usr/libexec/java_home для возврата местоположения JDK по умолчанию.

    2.2 Кроме того, найдите все установленные JDK.

    2.3 Кроме того, выполните указанную команду JDK.

    3. $$JAVA_HOME и mac OS 11 Биг Сур

    На macOS 10.15 Каталина и более поздние версии, зш является оболочкой терминала по умолчанию, и мы можем установить переменную среды $JAVA_HOME в любом

    3.2 Добавьте следующее содержание

    3.3 Создайте исходный файл и распечатайте $JAVA_HOME , готово.

    4. $JAVA_HOME и Mac OS X 10.5 Леопард

    Для более старых Mac OS X оболочка терминала по умолчанию bash , и мы можем установить переменную среды $JAVA_HOME в любом

    4.2 Добавьте следующий контент

    4.3 Создайте исходный файл и распечатайте $JAVA_HOME

    5. $JAVA_HOME и более старые версии Mac OS X

    В более старой версии Mac OS X инструмент /usr/libexec/java_home не существует, и нам нужно установить $JAVA_HOME на реальный путь.

    5.2 Добавьте следующий контент

    5.3 Создайте исходный файл и распечатайте $JAVA_HOME

    6. Переключение между различными версиями JDK

    Например, эта macOS содержит четыре JDK: 1.8, 14, 15 и 16, а JDK по умолчанию равен 16.

    6.1 Для zsh оболочки отредактируйте

    6.2 /usr/libexec/java_home -v»<$Версия>» для активации указанной версии JDK.

    Добавьте следующее содержимое для активации JDK 1.8

    Если мы хотим JDK 14.

    Если мы хотим JDK 15.

    6.3 Создайте исходный файл и распечатайте $JAVA_HOME , готово.

    Источник

    How to Set JAVA_HOME on MAC

    In this tutorial, I am going to share with you how to set the JAVA_HOME environment variable on a new MAC. The new way of setting JAVA_HOME environment variable allows us to dynamically identify and use the current Java version installed on a computer as well as let us switch between Java versions if there is more than one installed.

    Starting from Mac OS 10.5 there is a very convenient command that we can use to identify the installed Java version. For example, open the terminal window on your Mac and type the following command to print out the top Java version installed on your Mac

    If you have more than one version installed and you want to see all of the versions available, then run the following command in the terminal window.

    To print the current Java version installed, simply use

    Set JAVA_HOME Environment Variable

    To set the JAVA_HOME environment variable for a current user you will need to update the

    /.profile file. I will use the vi text editor on Mac but you can use the text editor of your choice.

      Open the terminal windows and type:

    This will open the .profile file for editing.
    Add the following line

    The /usr/libexec/java_home will return the current version of Java installed on the Mac computer.

  • Save the file by tapping on ESC button on the keyboard and then :wq. This will save the file and will quite.
  • In the terminal window type

    to apply changes to the .profile file right away.
    In the terminal window type

    This will print out the current Java version installed on your Mac computer.

    Switch Between Java Versions

    If you have more than one Java version installed on your computer and you need to switch to using a different version, you can do so by adding the -v flag.

    Let’s have a look at a short example.

    To learn what Java versions I have installed on my Mac computer I will type the following in the terminal window:

    this will return

    Which tells that there are two Java versions installed and the top version is “jdk-13.0.1.jdk“.

    To set a specific Java version I will need to:

      In the terminal window type

    To open the .profile file for editing.
    Add Java version I want to set. Like so:

    or if I wanted to set Java version 13, I would do it this way

  • Save the file by tapping on ESC button on your keyboard and then :wq. This will save the file and will quite.
  • Apply changes by typing
  • Now if you check Java version by typing

    It should print the current Java version set in JAVA_HOME.

    Источник

    How to set JAVA_HOME environment variable on macOS?

    According to this mobilefirst tutorial, it mentioned:

    You must have the JAVA_HOME environment variable set to your JDK directory.

    Mac OSX: /Library/Java/JavaVirtualMachines/jdk1.7.0_67.jdk/Contents/Home

    I’ve added this 2 lines in .bash_profile:

    Is this correct?

    4 Answers 4

    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

    Adding the below answer to help those who are looking for step by step instructions on how to setup Java_Home on a Mac.

    Determine whether Java is installed by using the command below:

    You will something like this — /usr/bin/java

    Next Step will be to determine the version of Java Installed by using the command below:

    You will see something like java version «1.8.0_131»

    Next step will be to get the location where the Java is installed:

    Under the Java folder, select the folder with the version that was displayed earlier:

    Next check if Java_Home is setup to the correct location:

    It will result in blank output if it is not already setup. If it returns the location, check if it points to the correct folder.

    You can add or update the Java_Home using the below commands:

    Navigate to the end of the file by pressing «Shift + g». Now press «i» to get to insert mode. Add the below lines in the bash_profile after replacing the path to the java home directory on your mac

    Save this by pressing Esc followed by «:wq!»

    Finally open a new terminal window and test the variable is setup correctly:

    Источник

    How to set JAVA_HOME in Mac permanently?

    I am trying to set JAVA_HOME by entering export JAVA_HOME=/Library/Java/Home at terminal. It sets the JAVA_HOME for current session.

    How can I set it permanently?

    20 Answers 20

    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

    You can use /usr/libexec/java_home -v to get the path you need for JAVA_HOME . For instance, to get the path to the 1.7 JDK you can run /usr/libexec/java_home -v 1.7 and it will return the path to the JDK. In your .profile or .bash_profile just add

    and you should be good. Alternatively, try and convince the maintainers of java tools you use to make use of this method to get the version they need.

    To open ‘.bash_profile’ type the following in terminal :

    and add the following line to the file:

    Press CTRL+X to exit the bash. Press ‘Y’ to save changes.

    To check whether the path has been added, type following in terminal:

    I was facing the same issue in MAC Catalina, If I edit .bash_profile i found export JAVA_HOME=»/Library/Java/JavaVirtualMachines/jdk1.8.0_201.jdk/Contents/Home But When I run terminal echo $JAVA_HOME it was returning empty, Later I found that the file .zshrc was missing I created this file with

    Then edit it by nano .zshrc and wrote

    Which solves my issue permanently

    Installing Java on macOS 11 Big Sur :

    • the easiest way is to select OpenJDK 11 (LTS), the HotSpot JVM, and macOS x64 is to get the latest release here: adoptopenjdk.net
    • Select macOS and x64 and download the JDK (about 190 MB), which will put the OpenJDK11U-jdk_x64_mac_hotspot_11.0.9_11.pkg file into your

    /Downloads folder

  • Clicking on pkg file, will install into this location: /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk
  • Almost done. After opening a terminal, the successful installation of the JDK can be confirmed like so: java —version
    • output:
    • JAVA_HOME is an important environment variable and it’s important to get it right. Here is a trick that allows me to keep the environment variable current, even after a Java Update was installed. In

      /.zshrc , I set the variable like so: export JAVA_HOME=$(/usr/libexec/java_home)
      In previous macOS versions, this was done in

      /.bash_profile . Anyway, open a new terminal and verify: echo $JAVA_HOME

      • output: /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home

    Источник

    Mac OS X Hints