Windows get java path

  1. Find Java Location Using Command where java

  2. Find Java Location Using Command set JAVA_HOME

  3. Find Java Location Using Command dir /b /s java.exe

  4. Find Java Location Using Command gcm -All java in Windows PowerShell

How to Find Java Location in Windows

Today, we will see how to find out where Java is located in Windows. There are multiple ways and commands to do this; we will check out various commands that return the Java location windows.

Find Java Location Using Command where java

The most commonly used command to get the current location of Java in Windows is where java. This is a Windows command that works just like the whereis command in Linux Operating System. The where command is used to display the location of the executable. It usually uses a search pattern.

As shown below, when we run the command where java in the command line of Windows, it returns the location of java.exe.

Output:

C:\User\.jdks\openjdk-15.0.1\bin\java.exe

Find Java Location Using Command set JAVA_HOME

The next technique to get the location of Java in Windows is to use the command set JAVA_HOME. In Windows, the path of Java or JDK is stored in the environment variables. The location is stored in the variable named PATH, a list of directories that can be used to access certain programs like Java directly without writing the whole path.

We can set the path of Java by the command set JAVA_HOME and then specify the path. But if the value is already set, it will return the path set to the variable JAVA_HOME. It completes our goal as this is the directory in which Java is located.

C :\Users\Rupam Saini > set JAVA_HOME

Output:

JAVA_HOME=C:\Users\Rupam Saini\.jdks\openjdk-15.0.1

Find Java Location Using Command dir /b /s java.exe

The dir command shows all the folders and sub-folders in the current location. We can use this command to get the locations of Java as there might be more than one executable of Java in a single Windows machine as some programs use their own Java environment.

We use the dir command with three parameters, first is /b that displays only the directory path without any extra details. In contrast, the /s parameter lists every occurrence of the specified file in the current directory and subdirectories, and at last, the execute name that is java.exe.

C :\User > dir / b / s java.exe

Output:

C:\User\.jdks\openjdk-15.0.1\bin\java.exe
C:\User\AppData\Local\JetBrains\IntelliJ IDEA Community Edition 2020.3\jbr\bin\java.exe

Find Java Location Using Command gcm -All java in Windows PowerShell

In all the examples in this tutorial, we use the traditional command-line,, but this method requires the Windows PowerShell, a command-line but with advanced capabilities. In PowerShell, we use the gcm command that is short for get-command. It returns all the commands in the machine.

We use gcm with two parameters; the first is -All that shows all the instances of the command in the current machine, and the second parameter is the command name. In our case, the command name is java. In return, it outputs some details about the command like the Command Type, the name of the executable executed on command, the version, and the executable source. The source is where Java is located.

PS C:\User> gcm -All java

Output:

CommandType     Name                                               Version    Source
-----------     ----                                               -------    ------
Application     java.exe                                           15.0.1.0   C:\User\.jdks\openjdk-15...

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

Last Updated :
17 May, 2024

PATH is an environment variable that is used by Operating System to locate the exe files (.exe) or java binaries ( java or javac command). The path once it is set, cannot be overridden. The PATH variable prevents us from having to write out the entire path to a program on the Command Line Interface every time we run it. Moreover, the path is just a variable that stores a bunch of shortcuts.

To execute Java console-based programs in Windows or Linux environments, we have to use Java and javac commands. The commands java and javac are not known to the operating system as we don’t specify where the executables reside. Hence, we need to specify the path where the executables are located. This is the reason we set the path and specify the path of the bin folder because the bin contains all binary executable files. After setting the path, it can load all necessary items in the program including the compiler or interpreter itself. 

Below is the procedure for how to set Java Path in both Windows and Linux?

To Set Java Path in Windows

Step 1: Go to the Search box and type Advanced System settings in it. Now click on the View Advanced System settings.

to-set-java-path-in-windows

Step 2: Select the Advanced tab and then click environment variables.

Step 3: In the system, variables click the New button. Now in the edit System variable, type variable name as JAVA_HOME and variable path as the path where the JDK folder is saved and click on OK button Usually the path of the JDK file will be C:\Program Files\Java\jdk1.8.0_60.

Step 4: Now in the system variables go to the path and click the Edit button.

Step 5: Click the New button.

Step 6: Now add the following path: %JAVA_HOME%\bin

To Find Java Path in Windows:

Here are the simple steps to find your Java path in Windows:

Step 1: Open a Command Prompt window.

Type the following command and press Enter:

where java

Step 2: You should see the path to your Java installation printed in the Command Prompt. It will typically look something like this:

C:\Program Files\Java\jdk1.8.0_291\bin\java.exe

That’s it! You’ve found your Java path in Windows.

To Set Java Path in Linux

Follow the given steps to set Java Path in Linux —

  • Open the terminal and enter the following command: 
sudo nano /etc/environment.
  • A file will be opened and add the following command to that file:
JAVA_HOME = "YOUR_PATH". 
  • Replace YOUR_PATH with the JDK bin file path.
  • Now restart your computer or virtual machine that you are using (or) reload the file: source /etc/environment
  • You can test the path by executing
 echo $JAVA_HOME
  • If you get the output without any error, then you’ve set the path correctly.
  • If you get any errors, try repeating the procedure again.

To Find Java Path in Linux:

Here are the steps to find Java Path in Linux System —

Step 1: Open a Terminal window.

Step 2: Type the following command and press Enter:

which java

Step 3: You should see the path to your Java installation printed on the terminal. It will typically look something like this:

/usr/bin/java

That’s it! You’ve found your Java path in Linux.

Conclusion

So, this was all about how you can find and set Java path in Windows and Linux. If you also have other queries regarding setting Java Path, Java_Home variable and default Java path, You can also refer to the following frequently asked questions.

Пройдите тест, узнайте какой профессии подходите

Ситуация, когда требуется найти, где именно на компьютере установлен JDK (Java Development Kit), является типичной для новичков, которые только начинают изучать

Ситуация, когда требуется найти, где именно на компьютере установлен JDK (Java Development Kit), является типичной для новичков, которые только начинают изучать Java. Например, это может потребоваться для настройки среды разработки или для проверки версии установленного JDK.

Обычно для определения местоположения JDK используется системная переменная JAVAHOME, которая должна указывать на директорию установки JDK. Для проверки этого можно воспользоваться командной строкой и командой echo %JAVA_HOME%. Однако, если эта переменная не была настроена при установке JDK, команда вернет лишь ‘JAVAHOME’.

Итак, как же определить местоположение JDK на компьютере под управлением Windows? Для этого есть несколько способов.

1. Использование командной строки

Первый и самый простой способ — это использование команды where java в командной строке. Эта команда вернет путь к исполняемому файлу java.exe, который обычно расположен в директории установки JDK.

2. Использование реестра Windows

Если первый способ не работает, можно воспользоваться редактором реестра Windows. Для этого необходимо открыть редактор (вызвать команду regedit в командной строке), и перейти по следующему пути: HKEY_LOCAL_MACHINE -> SOFTWARE -> JavaSoft -> Java Development Kit. Здесь в подразделе с версией JDK будет ключ «JavaHome», который указывает на директорию установки JDK.

3. Поиск в директории «Программы»

Есть и третий способ для тех, кому не по душе работать с командной строкой и реестром. Можно просто открыть директорию «Программы» на системном диске и вручную найти там папку с установленным JDK.

Таким образом, есть несколько способов определить местоположение JDK на компьютере с Windows. Несмотря на то, что это может показаться сложной задачей для новичков, с некоторой практикой становится ясно, что это довольно просто.

[the_ad id=”684″]

Getting the path of current directory is often required when you need to access some files from code generally for reading text or properties files.

This article will explain 4 different ways to get the path of current working directory in java or from java code.

Method 1: Using System property
Java has defined some properties which are used to get information about its environment. One of such property is user.dir which gives the path of current working directory.

In order to retrieve the value of java properties, getProperty() method of java.lang.System class is used. This method is static and takes a string argument, which is the name of property.
Example,

String currentPath = System.getProperty("user.dir");
System.out.println("Current path is:: " + currentPath);

If you run this code from an IDE such as eclipse, then it will return the absolute path of the current project.
[the_ad id=”651″]
Method 2: Using File class
java.io.File class has a constructor which takes a string argument. This argument represents the path to which the file object points.

Providing an empty path means that the file object is pointed to the current folder. Invoke getAbsolutePath() on the file object to get the complete path of current directory as shown below.

// create file object for current folder
File file = new File("");
String currentPath = file.getAbsolutePath();
System.out.println("Current path is:: " + currentPath);

Method 3: Using Paths
java.nio.file.Paths class introduced in java 7 is a utility class that contains static methods related to paths. It has a static get() method which takes a string argument representing a file path and returns an object of java.nio.file.Path.

Supplying empty string to get() means the current working directory.
Path object points to a physical file and its toAbsolutePath() method returns another Path object containing the absolute path of the file.

Invoke toString() method on this Path object to get the path of current working directory.
Java program code for this method is given below.

Path currentDirectoryPath = Paths.get("").toAbsolutePath();
String currentPath = currentDirectoryPath.toString();
System.out.println("Current directory path:: " + currentPath);

[the_ad id=”644″]
Method 4: Using FileSystems class
For dealing with file system, java provides a class java.nio.file.FileSystem. Object of FileSystem can be retrieved using java.nio.file.FileSystems class using its static getDefault() method.

FileSystem has a getPath() method which takes a string argument representing the path of a file.
Supplying it an empty string means the current directory.
getPath() returns an object of Path and you can use its toAbsolutePath() method to get the full path of current directory.
Example,

FileSystem fileSystem = FileSystems.getDefault();
Path path = fileSystem.getPath("").toAbsolutePath()
String currentDirectoryPath = path.toString();

Above code can be written as one-liner

String currentDirectoryPath = FileSystems.getDefault().
                                          getPath("").
                                          toAbsolutePath().
                                          toString();

[the_ad id=”3385″]
Hope the article was useful, click the clap below if you liked it.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Athome video streamer windows
  • Стандартная звуковая схема windows 10
  • Как продолжить установку windows 11 без интернета
  • История использования компьютера windows 10
  • Windows keyboard shortcuts windows 7