PATH and CLASSPATH
This section explains how to use the PATH and CLASSPATH environment variables on Microsoft Windows, Solaris, and Linux. Consult the installation instructions included with your installation of the Java Development Kit (JDK) software bundle for current information.
After installing the software, the JDK directory will have the structure shown below.
The bin directory contains both the compiler and the launcher.
Update the PATH Environment Variable (Microsoft Windows)
You can run Java applications just fine without setting the PATH environment variable. Or, you can optionally set it as a convenience.
Set the PATH environment variable if you want to be able to conveniently run the executables ( javac.exe , java.exe , javadoc.exe , and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:
The PATH environment variable is a series of directories separated by semicolons ( ; ). Microsoft Windows looks for programs in the PATH directories in order, from left to right. You should have only one bin directory for the JDK in the path at a time (those following the first are ignored), so if one is already present, you can update that particular entry.
The following is an example of a PATH environment variable:
It is useful to set the PATH environment variable permanently so it will persist after rebooting. To make a permanent change to the PATH variable, use the System icon in the Control Panel. The precise procedure varies depending on the version of Windows:
- Select Start, select Control Panel. double click System, and select the Advanced tab.
- Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
- In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
- From the desktop, right click the My Computer icon.
- Choose Properties from the context menu.
- Click the Advanced tab (Advanced system settings link in Vista).
- Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
- In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
- From the desktop, right click the Computer icon.
- Choose Properties from the context menu.
- Click the Advanced system settings link.
- Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
- In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Update the PATH Variable (Solaris and Linux)
You can run the JDK just fine without setting the PATH variable, or you can optionally set it as a convenience. However, you should set the path variable if you want to be able to run the executables ( javac , java , javadoc , and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:
To find out if the path is properly set, execute:
This will print the version of the java tool, if it can find it. If the version is old or you get the error java: Command not found, then the path is not properly set.
To set the path permanently, set the path in your startup file.
For C shell ( csh ), edit the startup file (
For bash , edit the startup file (
For ksh , the startup file is named by the environment variable, ENV . To set the path:
For sh , edit the profile file (
Then load the startup file and verify that the path is set by repeating the java command:
For C shell ( csh ):
For ksh , bash , or sh :
Checking the CLASSPATH variable (All platforms)
The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes. (Classes that are part of the JRE, JDK platform, and extensions should be defined through other means, such as the bootstrap class path or the extensions directory.)
The preferred way to specify the class path is by using the -cp command line switch. This allows the CLASSPATH to be set individually for each application without affecting other applications. Setting the CLASSPATH can be tricky and should be performed with care.
The default value of the class path is ".", meaning that only the current directory is searched. Specifying either the CLASSPATH variable or the -cp command line switch overrides this value.
To check whether CLASSPATH is set on Microsoft Windows NT/2000/XP, execute the following:
On Solaris or Linux, execute the following:
If CLASSPATH is not set you will get a CLASSPATH: Undefined variable error (Solaris or Linux) or simply %CLASSPATH% (Microsoft Windows NT/2000/XP).
To modify the CLASSPATH , use the same procedure you used for the PATH variable.
Class path wildcards allow you to include an entire directory of .jar files in the class path without explicitly naming them individually. For more information, including an explanation of class path wildcards, and a detailed description on how to clean up the CLASSPATH environment variable, see the Setting the Class Path technical note.
. как установить Java на Windows?
Во многих моих тренингах так или иначе используется Java, либо как язык программирования для разработки автотестов, либо как виртуальная машина для запуска приложений, написанных на Java — инструментов тестирования, сред разработки, и даже клиент системы видеоконференций GotoWebinar требует наличия Java.
Поэтому я решил описать процедуру установки Java для операционной системы Windows и последующей настройки системы, потому что, к сожалению, недостаточно просто “запустить инсталлятор и всегда нажимать кнопку Next”.
1. Где взять Java?
2. Какую версию выбрать?
Разумеется, последнюю доступную (на момент написания инструкции это Java 8).
Выбирая из 32-битной и 64-битной версий, берите 64-битную, если ваша операционная система это позволяет, потому что у неё менее строгие ограничения по памяти, доступной исполняемым Java-приложениям.
3. Что устанавливать, JRE или JDK?
Java Runtime Environment, или JRE — это виртуальная машина, позволяющая запускать приложения, написанные на языке программирования Java.
Java Development Kit, или JDK — это набор инструментов, для разработки программ на языке программирования Java (компилятор, архиватор, генератор документации и прочие). JRE разумеется тоже входит в дистрибутив JDK.
Правило очень простое: если вы собираетесь что-нибудь писать на языке программирования Java, значит вам потребуется JDK. А если только запускать готовые программы — тогда достаточно JRE.
4. Установка Java
Вот тут, действительно, всё просто — нужно запустить инсталлятор и следовать указаниям визарда. Можно просто всё время нажимать кнопку Next.
5. Настройка переменных окружения
К сожалению, инсталлятор Java не выполняет настройку переменных окружения, поэтому придётся сделать это вручную после установки.
Во-первых, необходимо установить переменную JAVA_HOME , которая должна указывать на директорию, в которую установлена Java. Многие программы используют эту переменную, чтобы определить, где находится Java.
Во-вторых, надо в переменную PATH добавить путь к директории %JAVA_HOME%\bin . Эта переменная указывает операционной системе список директорий, в которых нужно искать исполняемые файлы, и чтобы можно было запускать Java из консоли, переменная PATH должна быть правильно настроена.
Для установки переменных окружения сначала нужно открыть свойства компьютера, либо использовав сочетание клавиш Win-Pause, либо через меню “Пуск”:
Затем нужно выбрать “Дополнительные параметры системы”, в открывшемся диалоге перейти на вкладку “Дополнительно” и нажать кнопку “Переменные среды”, после чего появится диалог настройки переменных окружения.

Если у вас уже есть переменная окружения JAVA_HOME — надо её отредактировать, если нет — создать новую. В качестве значения нужно указать путь к директории, куда установлена Java, то есть, например c:\Program Files\Java\jdk1.8.0_25\ , если вы установили JDK, либо c:\Program Files\Java\jre1.8.0_25\ , если вы установили только JRE.
После того, как вы установили значение переменной JAVA_HOME , необходимо отредактировать значение переменной PATH, добавив туда путь к директории, где находятся исполняемые файлы Java, то есть %JAVA_HOME%\bin

И сохранить всё это, закрыв все открытые диалоги в обратном порядке кнопками OK.
Обратите внимание, что если вы устанавливаете JDK, то в названии директории указывается номер версии, поэтому впоследствии, когда вы решите установить более новую версию, не забудьте поменять значение переменной окружения JAVA_HOME .
После того, как вы изменили переменные окружения, новые значения будут действительны только для новых запускаемых программ, уже запущенные программы не узнают о том, что переменные окружения поменялись. Поэтому если вы, например, пытались запустить Java из консоли и у вас не получилось из-за неправильных настроек переменной PATH , вам придётся перезапустить консоль после того, как вы поменяли значение переменной.
6. Удаление лишних файлов
Запустите консоль ( cmd ) и выполните в ней команду where java .
В результате вы должны увидеть путь к исполняемому файлу java.exe , который операционная система должна успешно обнаружить в том месте, куда вы установили Java. Если файл не нашёлся — значит неправильно настроена переменная PATH и нужно вернуться к предыдущему пункту.
Однако иногда бывает и наоборот, находятся «лишние» исполняемые файлы:

Происходит это из-за того, что инсталлятор Java вместо того, чтобы правильно настроить переменные окружения, пытается положить исполняемые файлы в директорию C:\Windows\system32
Это не очень хорошо — засоряется системная директория, может возникнуть рассогласование версий Java (в разных директориях разные версии). Поэтому надо удалить из каталога C:\Windows\system32 исполняемые файлы java.exe , javaw.exe и javaws.exe , если они там обнаружатся.
Вот и всё, теперь можно пользоваться Java. Только не забывайте о том, что после установки новой версии надо будет обновить переменную окружения JAVA_HOME !

Автор: Алексей Баранцев
Если вам понравилась эта статья, вы можете поделиться ею в социальных сетях (кнопочки ниже), а потом вернуться на главную страницу блога и почитать другие мои статьи.
Ну а если вы не согласны с чем-то или хотите что-нибудь дополнить – оставьте комментарий ниже, может быть это послужит поводом для написания новой интересной статьи.
Найти местоположение Java в Windows

Сегодня мы увидим, как узнать, где находится Java в Windows. Для этого есть несколько способов и команд; мы проверим различные команды, которые возвращают окна местоположения Java.
Найдите местоположение Java с помощью команды where java
Наиболее часто используемая команда для получения текущего местоположения Java в Windows — это where java . Это команда Windows, которая работает так же, как команда whereis в операционной системе Linux. Команда where используется для отображения местоположения исполняемого файла. Обычно используется шаблон поиска.
Как показано ниже, когда мы запускаем команду where java в командной строке Windows, она возвращает местоположение java.exe .
Найдите местоположение Java с помощью команды set JAVA_HOME
Следующий способ узнать местоположение Java в Windows — использовать команду установить JAVA_HOME . В Windows путь к Java или JDK хранится в переменных среды. Местоположение хранится в переменной с именем PATH , списке каталогов, которые можно использовать для прямого доступа к определенным программам, таким как Java, без записи всего пути.
Мы можем установить путь к Java командой set JAVA_HOME , а затем указать путь. Но если значение уже установлено, он вернет путь, установленный к переменной JAVA_HOME . Это завершает нашу задачу, поскольку это каталог, в котором находится Java.
Найдите местоположение Java с помощью команды dir /b /s java.exe
Команда dir показывает все папки и подпапки в текущем местоположении. Мы можем использовать эту команду для получения местоположения Java, поскольку на одном компьютере с Windows может быть более одного исполняемого файла Java, поскольку некоторые программы используют свою собственную среду Java.
Мы используем команду dir с тремя параметрами, первым из которых является /b , который отображает только путь к каталогу без каких-либо дополнительных деталей. Напротив, параметр /s перечисляет все вхождения указанного файла в текущем каталоге и подкаталогах и, наконец, имя выполнения java.exe .
Найдите местоположение Java с помощью команды gcm -All java в Windows PowerShell
Во всех примерах в этом руководстве мы используем традиционную командную строку, но для этого метода требуется Windows PowerShell, командная строка, но с расширенными возможностями. В PowerShell мы используем команду gcm , сокращенно от get-command . Он возвращает все команды в машине.
Мы используем gcm с двумя параметрами; первый — -All , который показывает все экземпляры команды на текущей машине, а второй параметр — это имя команды. В нашем случае имя команды java . В свою очередь, он выводит некоторые сведения о команде, такие как тип команды, имя исполняемого файла, выполняемого по команде, версия и источник исполняемого файла. Источник — это место, где находится Java.
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
How do I find where JDK is installed on my windows machine?
On running Java -version in cmd, it shows the version as ‘1.6.xx’. To find the location of this SDK on my machine I tried using echo %JAVA_HOME% but it is only showing ‘JAVA_HOME’ (as there is no ‘JAVA_PATH’ var set in my environment variables).
![]()
25 Answers 25
If you are using Linux/Unix/Mac OS X:
Should output the exact location.
After that, you can set JAVA_HOME environment variable yourself.
In my computer (Mac OS X — Snow Leopard):
If you are using Windows:
Windows > Start > cmd >
If you have a JDK installed, the Path is displayed,
for example: C:\Program Files\Java\jdk1.6.0_30\bin\javac.exe
In Windows at the command prompt
$PATH:i, but as you wrote, it won't work if you didn't set it in the PATH.
Command line:
Run where java on Command Prompt.

GUI:
On Windows 10 you can find out the path by going to Control Panel > Programs > Java. In the panel that shows up, you can find the path as demonstrated in the screenshot below. In the Java Control Panel, go to the ‘Java’ tab and then click the ‘View’ button under the description ‘View and manage Java Runtime versions and settings for Java applications and applets.’
This should work on Windows 7 and possibly other recent versions of Windows.

![]()
In windows the default is: C:\Program Files\Java\jdk1.6.0_14 (where the numbers may differ, as they’re the version).
Java installer puts several files into %WinDir%\System32 folder (java.exe, javaws.exe and some others). When you type java.exe in command line or create process without full path, Windows runs these as last resort if they are missing in %PATH% folders.
You can lookup all versions of Java installed in registry. Take a look at HKLM\SOFTWARE\JavaSoft\Java Runtime Environment and HKLM\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment for 32-bit java on 64 bit Windows.
This is how java itself finds out different versions installed. And this is why both 32-bit and 64-bit version can co-exist and works fine without interfering.
Plain and simple on Windows platforms:
where java
Under Windows, you can use
to print the full path of each and every «java.exe» on your C: drive, regardless of whether they are on your PATH environment variable.
The batch script below will print out the existing default JRE. It can be easily modified to find the JDK version installed by replacing the Java Runtime Environment with Java Development Kit.
![]()
In a Windows command prompt, just type:
Or, if you don’t like the command environment, you can check it from:
Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced tab > Environment Variables and in system variable try to find JAVA_HOME.

![]()
Powershell one liner:
In Windows PowerShell you can use the Get-Command function to see where Java is installed:
The -All part makes sure to show all places it appears in the Path lookup. Below is example output.