Changing java path windows

Установка Java (JDK) в Windows и Linux, переменная PATH и JAVA_HOME

Java — язык общего назначения, основанных на классах, поддерживающий многопоточность и являющийся объектно-ориентированным. Программы на Java компилируются в так называемый byte-код, который в свою очередь запускается Виртуальной Машиной Java (Java Virtual Machine — JVM), независимо от архитектуры компьютера. На данный момент последняя версия Java двенадцатая.

Ниже мы рассмотрим — как установить Java на Windows и Linux. Для каждой из платформ создана своя версия JDK, JRE и JVM, хотя сами программы на Java и не меняются от платформы к платформе (что логично).

Давайте проясним несколько вещей перед тем, как мы начнем.

  • JDK (Java Development Kit) — эта штука нужна для разработчиков на Java (то есть нас) и включает в себя инструменты разработки, документирования, упаковки и так далее (в том числе компилятор Javac, Javadoc, Jar-упаковщик и дебаггер).
  • JRE (Java Runtime Environment) — сюда включены библиотеки Java, которые необходимы для запуска Java-программ. Эта штука нужна обычным пользователям и не содержит инструментов для разработки.
  • JVM (Java Virtual Machine) — это и есть сама виртуальная машина Java, которая непосредственно и запускает наши Java-программы (байткод). Ее реализация написана для множества железа и платформ.

Установка Java (JDK) в Windows

Первым делом необходимо скачать JDK с официальной страницы Oracle. В нашем случае нужна версия под Windows, в самом низу.

После установки запустите скачанный exe-файл и установите его на ваш компьютер. Как только вы это сделаете, нужно будет настроить окружение.

Перейдите в Панель управления -> Система и безопасность -> Система. На вкладке «Дополнительно» нажмите на «Переменные среды», как показано ниже:

Теперь нужно найти и дополнить переменную PATH так, чтобы она содержала путь до установленной Java. Выберите PATH и нажмите «Изменить»:

Вы увидите список уже установленных переменных. Сейчас необходимо нажать «Новый» и добавить путь, по которому установлена Java (каталог bin!). По умолчанию это обычно «C:\Program Files(x86)\Java\jdk\bin».

Читайте также:  Удаление последних обновлений windows 10 cmd

Нажмите «Готово» (или «Ок»), сохраните настройки и на этом всё готово! Чтобы проверить, что установка прошла корректно, откройте консоль и введите:

Если вы получили сведения о версии Java, значит всё хорошо.

Установка Java (JDK) на Linux

В Linux есть несколько способов установить Java. Мы опишем самый простой и быстрый, с использование терминала. И в данном случае мы установим OpenJDK. OpenJDK — это бесплатная и свободная реализация виртуальной машины Java, причем очень популярная.

Откройте терминал и напишите команду для установки пакета:

Осталось подтвердить установку и на этом всё, Java установлена! Единственное, что меняется — это прописывание путей до компилятора.

Чтобы прописать JAVA_HOME в окружение, выполните следующую команду (только убедитесь, что такой каталог уже есть):

Чтобы прописать компилятор Java в PATH, выполните другую команду (опять же, ваши пути до Java могут отличаться от моих):

На этом установка закончена. Чтобы проверить, что всё работает правильно, достаточно написать в терминале:

О том, как же всё-таки писать на Java, мы расскажем в следующий раз.

Changing JAVA_HOME in cmd temporarily doesn’t change PATH temporarily in windows

I hava defined JAVA_HOME to jdk11 in users’ environment variable and PATH contains %JAVA_HOME%/bin in it.

Now I want to switch to jdk8 temporarily in command-prompt ( cmd ) by changing JAVA_HOME to jdk8 but it doesn’t change value in path or java -version doesn’t change in current instance of cmd.

P.S.- I have deleted c:\Program Data\Oracle\java.. files to be avoid any confusion

3 Answers 3

It doesn’t change value in path or java -version doesn’t change in current instance of cmd

You have to restart cmd for the changes to take effect as a cmd shell inherits it environment from the parent process.

So what is the correct way to switch between Java versions from the command line?

Use a set of batch files, as follows:

Being a Java developer, I always compile and test my code on different Java versions. But switching between them is a huge problem. So finally I found an easy method to do this. You have to create following batch files and place them in directory you open your command line in or in SYSTEM PATH. You can use you favorite text editor to create these files.

Make sure you assign the appropriate JAVA_HOME value in batch files, according to your Java installation. Whenever you want to switch between Java versions, just run the respective batch file and you are done.

Note: JAVA_HOME and the path to java must always refer to the exact same version of the JDK . If you mix them up, unpredictable things will happen!

Читайте также:  Virtualbox windows linux ubuntu

How can I change the Java Runtime Version on Windows (7)?

How can I change the Java Runtime Version on Windows.

I installed Java 7 for some tests, and now I need the old java6 as system default, but I don’t want to uninstall the Java 7 (I need it for later tests). Can I change the system-used JRE in the control panel/Java/JRE tab? I can change/edit/add/delete the user-used version, but not the system-used.

8 Answers 8

For Java applications, i.e. programs that are delivered (usually) as .jar files and started with java -jar xxx.jar or via a shortcut that does the same, the JRE that will be launched will be the first one found on the PATH .

If you installed a JRE or JDK, the likely places to find the .exe s are below directories like C:\Program Files\JavaSoft\JRE\x.y.z . However, I’ve found some «out of the box» Windows installations to (also?) have copies of java.exe and javaw.exe in C:\winnt\system32 (NT and 2000) or C:\windows\system (Windows 95, 98). This is usually a pretty elderly version of Java: 1.3, maybe? You’ll want to do java -version in a command window to check that you’re not running some antiquated version of Java.

You can of course override the PATH setting or even do without it by explicitly stating the path to java.exe / javaw.exe in your command line or shortcut definition.

If you’re running applets from the browser, or possibly also Java Web Start applications (they look like applications insofar as they have their own window, but you start them from the browser), the choice of JRE is determined by a set of registry settings:

More registry keys are created using this scheme:

i.e. one for the major and one including the minor version number. Each of these keys has values like these (examples shown):

. and your browser will look to these settings to determine which JRE to fire up.

Since Java versions are changing pretty frequently, there’s now a «wizard» called the «Java Control Panel» for manually switching your browser’s Java version. This works for IE, Firefox and probably others like Opera and Chrome as well: It’s the ‘Java’ applet in Windows’ System Settings app. You get to pick any one of the installed JREs. I believe that wizard fiddles with those registry entries.

If you’re like me and have «uninstalled» old Java versions by simply wiping out directories, you’ll find these «ghosts» among the choices too; so make sure the JRE you choose corresponds to an intact Java installation!

Читайте также:  Mac os разбить флешку

Some other answers are recommending setting the environment variable JAVA_HOME . This is meanwhile outdated advice. Sun came to realize, around Java 2, that this environment setting is

  1. unreliable, as users often set it incorrectly, and
  2. unnecessary, as it’s easy enough for the runtime to find the Java library directories, knowing they’re in a fixed path relative to the path from which java.exe or javaw.exe was launched.

There’s hardly any modern Java software left that needs or respects the JAVA_HOME environment variable.

. and some useful information on multi-version support:

How to set JAVA_HOME on Windows 10?

This tutorial shows you how to set a JAVA_HOME system variable on Windows 10.

1. Advanced System Settings

Type advanced system settings in the search box (beside the Windows start button), clicks View advanced system settings .

2. Environment Variables

Select Advance tab, clicks Environment Variables

3. Add JAVA_HOME

In System variables, clicks New. button to add a new JAVA_HOME variable and point it to the JDK installed folder.

  1. Correct – C:\Program Files\Java\jdk1.8.0_60
  2. Wrong – C:\Program Files\Java\jdk1.8.0_60\bin

4. Update PATH

In System variables, find PATH , clicks edit. button :

4.1 In old version of Windows, it will prompt you below dialog box to edit the values directly, append this %JAVA_HOME%\bin; to the end of the line.

4.2 In latest Windows 10, it will prompt you below dialog box, clicks on New button, and add this %JAVA_HOME%\bin

Window add Java to Path

I used to use My Computer -> Environment variables to set up PATH for Java, but where can I find the same in Windows 8?

2 Answers 2

Type: Control Panel

In the control panel search box, enter:

Edit environment variables for your account

Edit the system environment variables

The environment variable dialog itself is very similar to the one under previous versions of Windows.

Set Environment variable using Command Prompt in easy two steps:

Example of windows SET command:

Step 1. Print the PATH environment variable

Step 2. Add one variable to path ( For example : Java SDK )

Verify the Change

Not the answer you’re looking for? Browse other questions tagged java windows path or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

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