I need to know where JDK is located on my 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).
asked Jan 13, 2011 at 14:26
3
If you are using Linux/Unix/Mac OS X:
Try this:
$ which java
Should output the exact location.
After that, you can set JAVA_HOME
environment variable yourself.
In my computer (Mac OS X — Snow Leopard):
$ which java
/usr/bin/java
$ ls -l /usr/bin/java
lrwxr-xr-x 1 root wheel 74 Nov 7 07:59 /usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java
If you are using Windows:
c:> for %i in (java.exe) do @echo. %~$PATH:i
answered Jan 13, 2011 at 14:28
Pablo Santa CruzPablo Santa Cruz
176k32 gold badges240 silver badges292 bronze badges
7
Windows > Start > cmd >
C:> for %i in (javac.exe) do @echo. %~$PATH:i
If you have a JDK installed, the Path is displayed,
for example: C:Program FilesJavajdk1.6.0_30binjavac.exe
answered May 9, 2012 at 16:29
grokstergrokster
5,8591 gold badge36 silver badges22 bronze badges
5
In Windows at the command prompt
where javac
answered Jul 25, 2013 at 12:02
NanoBennettNanoBennett
1,7421 gold badge12 silver badges13 bronze badges
5
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.
answered Jul 26, 2017 at 18:46
smartexpertsmartexpert
2,5653 gold badges24 silver badges41 bronze badges
4
In windows the default is: C:Program FilesJavajdk1.6.0_14
(where the numbers may differ, as they’re the version).
answered Oct 24, 2013 at 21:24
Ronen RabinoviciRonen Rabinovici
8,5645 gold badges34 silver badges46 bronze badges
3
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 HKLMSOFTWAREJavaSoftJava Runtime Environment and HKLMSOFTWAREWow6432NodeJavaSoftJava 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.
answered Feb 1, 2012 at 10:48
Plain and simple on Windows platforms:
where java
answered Jan 25, 2014 at 16:33
luccaaluccaa
2973 silver badges2 bronze badges
1
Under Windows, you can use
C:>dir /b /s java.exe
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.
answered Nov 24, 2015 at 17:03
0
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.
@echo off
setlocal
::- Get the Java Version
set KEY="HKLMSOFTWAREJavaSoftJava Runtime Environment"
set VALUE=CurrentVersion
reg query %KEY% /v %VALUE% 2>nul || (
echo JRE not installed
exit /b 1
)
set JRE_VERSION=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JRE_VERSION=%%b
)
echo JRE VERSION: %JRE_VERSION%
::- Get the JavaHome
set KEY="HKLMSOFTWAREJavaSoftJava Runtime Environment%JRE_VERSION%"
set VALUE=JavaHome
reg query %KEY% /v %VALUE% 2>nul || (
echo JavaHome not installed
exit /b 1
)
set JAVAHOME=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JAVAHOME=%%b
)
echo JavaHome: %JAVAHOME%
endlocal
answered Aug 11, 2014 at 18:21
munsinghmunsingh
3172 silver badges9 bronze badges
In a Windows command prompt, just type:
set java_home
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.
answered Mar 16, 2014 at 11:36
JohannJohann
26.9k39 gold badges165 silver badges273 bronze badges
1
In Windows PowerShell you can use the Get-Command
function to see where Java is installed:
Get-Command -All java
Or
gcm -All java
The -All
part makes sure to show all places it appears in the Path lookup. Below is example output.
PS C:> gcm -All java
CommandType Name Version Source
----------- ---- ------- ------
Application java.exe 8.0.202.8 C:Program Files (x86)Common FilesOracleJavajav...
Application java.exe 8.0.131... C:ProgramDataOracleJavajavapathjava.exe
answered Nov 9, 2020 at 17:32
Scott HScott H
2,58424 silver badges28 bronze badges
Powershell one liner:
$p='HKLM:SOFTWAREJavaSoftJava Development Kit'; $v=(gp $p).CurrentVersion; (gp $p/$v).JavaHome
answered Jun 17, 2017 at 8:15
majkinetormajkinetor
8,6929 gold badges54 silver badges72 bronze badges
1
Run this program from commandline:
// File: Main.java
public class Main {
public static void main(String[] args) {
System.out.println(System.getProperty("java.home"));
}
}
$ javac Main.java
$ java Main
answered Jan 13, 2011 at 14:29
PeterMmmPeterMmm
24.1k13 gold badges71 silver badges111 bronze badges
2
More on Windows… variable java.home is not always the same location as the binary that is run.
As Denis The Menace says, the installer puts Java files into Program Files, but also java.exe into System32. With nothing Java related on the path java -version can still work. However when PeterMmm’s program is run it reports the value of Program Files as java.home, this is not wrong (Java is installed there) but the actual binary being run is located in System32.
One way to hunt down the location of the java.exe binary, add the following line to PeterMmm’s code to keep the program running a while longer:
try{Thread.sleep(60000);}catch(Exception e) {}
Compile and run it, then hunt down the location of the java.exe image. E.g. in Windows 7 open the task manager, find the java.exe entry, right click and select ‘open file location’, this opens the exact location of the Java binary. In this case it would be System32.
answered Oct 24, 2012 at 10:23
Moika TurnsMoika Turns
66710 silver badges17 bronze badges
Have you tried looking at your %PATH% variable. That’s what Windows uses to find any executable.
answered Jan 13, 2011 at 14:28
sblundysblundy
60.5k22 gold badges121 silver badges123 bronze badges
1
Just execute the set
command in your command line. Then you see all the environments variables you have set.
Or if on Unix you can simplify it:
$ set | grep "JAVA_HOME"
answered Jan 13, 2011 at 14:31
1
This is OS specific. On Unix:
which java
will display the path to the executable. I don’t know of a Windows equivalent, but there you typically have the bin
folder of the JDK installation in the system PATH
:
echo %PATH%
answered Jan 13, 2011 at 14:30
Michael BorgwardtMichael Borgwardt
341k78 gold badges481 silver badges718 bronze badges
2
On macOS, run:
cd /tmp && echo 'public class Main {public static void main(String[] args) {System.out.println(System.getProperty("java.home"));}}' > Main.java && javac Main.java && java Main
On my machine, this prints:
/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
Note that running which java
does not show the JDK location, because the java
command is instead part of JavaVM.framework
, which wraps the real JDK:
$ which java
/usr/bin/java
/private/tmp
$ ls -l /usr/bin/java
lrwxr-xr-x 1 root wheel 74 14 Nov 17:37 /usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java
answered Jan 18, 2018 at 13:58
jameshfisherjameshfisher
33.2k30 gold badges116 silver badges166 bronze badges
None of these answers are correct for Linux if you are looking for the home that includes the subdirs such as: bin, docs, include, jre, lib, etc.
On Ubuntu for openjdk1.8.0, this is in:
/usr/lib/jvm/java-1.8.0-openjdk-amd64
and you may prefer to use that for JAVA_HOME
since you will be able to find headers if you build JNI source files. While it’s true which java
will provide the binary path, it is not the true JDK home.
answered Jan 27, 2016 at 1:33
EntangledLoopsEntangledLoops
1,9091 gold badge23 silver badges36 bronze badges
I have improved munsingh’s answer above by testing for the registry key in 64-bit and 32-bit registries, if needed:
::- Test for the registry location
SET VALUE=CurrentVersion
SET KEY_1="HKLMSOFTWAREJavaSoftJava Development Kit"
SET KEY_2=HKLMSOFTWAREJavaSoftJDK
SET REG_1=reg.exe
SET REG_2="C:Windowssysnativereg.exe"
SET REG_3="C:Windowssyswow64reg.exe"
SET KEY=%KEY_1%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
::- %REG_2% is for 64-bit installations, using "C:Windowssysnative"
SET KEY=%KEY_1%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
::- %REG_3% is for 32-bit installations on a 64-bit system, using "C:Windowssyswow64"
SET KEY=%KEY_1%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
:_set_value
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
SET JDK_VERSION=%%b
)
SET KEY=%KEY%%JDK_VERSION%
SET VALUE=JavaHome
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
SET JAVAHOME=%%b
)
ECHO "%JAVAHOME%"
::- SETX JAVA_HOME "%JAVAHOME%"
reference for access to the 64-bit registry
answered Mar 28, 2018 at 17:51
JohnP2JohnP2
1,87919 silver badges17 bronze badges
Maybe the above methods work… I tried some and didn’t for me. What did was this :
Run this in terminal :
/usr/libexec/java_home
answered Oct 17, 2020 at 3:13
Mudit VermaMudit Verma
3542 silver badges6 bronze badges
Simple method (Windows):
Open an application using java.
press ctrl + shift + esc
Right click on OpenJDK platform binary. Click open file location.
Then it will show java/javaw.exe then go to the top where it shows the folder and click on the jdk then right copy the path, boom. (Wont work for apps using bundled jre paths/runtimes, because it will show path to the bundled runtime)
Dharman♦
30.3k22 gold badges84 silver badges132 bronze badges
answered Oct 3, 2021 at 5:59
deateaterOGdeateaterOG
1113 silver badges9 bronze badges
in Windows cmd:
set "JAVA_HOME"
answered Dec 25, 2014 at 17:42
HusamHusam
132 bronze badges
0
#!/bin/bash
if [[ $(which ${JAVA_HOME}/bin/java) ]]; then
exe="${JAVA_HOME}/bin/java"
elif [[ $(which java) ]]; then
exe="java"
else
echo "Java environment is not detected."
exit 1
fi
${exe} -version
For windows:
@echo off
if "%JAVA_HOME%" == "" goto nojavahome
echo Using JAVA_HOME : %JAVA_HOME%
"%JAVA_HOME%/bin/java.exe" -version
goto exit
:nojavahome
echo The JAVA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program.
goto exit
:exit
This link might help to explain how to find java executable from bash: http://srcode.org/2014/05/07/detect-java-executable/
answered May 8, 2014 at 7:01
2
Script for 32/64 bit Windows.
@echo off
setlocal enabledelayedexpansion
::- Get the Java Version
set KEY="HKLMSOFTWAREJavaSoftJava Runtime Environment"
set KEY64="HKLMSOFTWAREWOW6432NodeJavaSoftJava Runtime Environment"
set VALUE=CurrentVersion
reg query %KEY% /v %VALUE% 2>nul || (
set KEY=!KEY64!
reg query !KEY! /v %VALUE% 2>nul || (
echo JRE not installed
exit /b 1
)
)
set JRE_VERSION=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JRE_VERSION=%%b
)
echo JRE VERSION: %JRE_VERSION%
::- Get the JavaHome
set KEY="HKLMSOFTWAREJavaSoftJava Runtime Environment%JRE_VERSION%"
set KEY64="HKLMSOFTWAREWOW6432NodeJavaSoftJava Runtime Environment%JRE_VERSION%"
set VALUE=JavaHome
reg query %KEY% /v %VALUE% 2>nul || (
set KEY=!KEY64!
reg query !KEY! /v %VALUE% 2>nul || (
echo JavaHome not installed
exit /b 1
)
)
set JAVAHOME=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JAVAHOME=%%b
)
echo JavaHome: %JAVAHOME%
endlocal
answered Mar 26, 2019 at 23:23
RudixxRudixx
1051 gold badge1 silver badge7 bronze badges
How to set the environment variables for Java in Windows (the classpath)?
xpt
19.7k36 gold badges121 silver badges211 bronze badges
asked Nov 4, 2009 at 7:54
5
Java SE Development Kit 8u112 on a 64-bit Windows 7 or Windows 8
Set the following user environment variables (== environment variables of type user variables)
JAVA_HOME :
C:Program FilesJavajdk1.8.0_112
JDK_HOME :
%JAVA_HOME%
JRE_HOME :
%JAVA_HOME%jre
CLASSPATH :
.;%JAVA_HOME%lib;%JAVA_HOME%jrelib
PATH :
your-unique-entries;%JAVA_HOME%bin
(make sure that the longishyour-unique-entries
does not contain any other references to another Java installation folder.
Note for Windows users on 64-bit systems:
Progra~1 = 'Program Files'
Progra~2 = 'Program Files(x86)'
Notice that these environment variables are derived from the «root» environment variable JAVA_HOME
. This makes it easy to update your environment variables when updating the JDK. Just point JAVA_HOME
to the fresh installation.
There is a blogpost explaining the rationale behind all these environment variables.
Optional recommendations
- Add a user environment variable
JAVA_TOOL_OPTIONS
with value-Dfile.encoding="UTF-8"
. This ensures that Java (and tools such as Maven) will run with aCharset.defaultCharset()
ofUTF-8
(instead of the defaultWindows-1252
). This has saved a lot of headaches when wirking with my own code and that of others, which unfortunately often assume the (sane) default encoding UTF-8. - When JDK is installed, it adds to the system environment variable
Path
an entryC:ProgramDataOracleJavajavapath;
. I anecdotally noticed that the links in that directory didn’t get updated during an JDK installation update. So it’s best to removeC:ProgramDataOracleJavajavapath;
from thePath
system environment variable in order to have a consistent environment.
user
14.4k6 gold badges25 silver badges123 bronze badges
answered Oct 29, 2014 at 21:00
AbdullAbdull
26k26 gold badges128 silver badges170 bronze badges
15
In Windows inorder to set
Step 1 : Right Click on MyComputer and click on properties .
Step 2 : Click on Advanced tab
Step 3: Click on Environment Variables
Step 4: Create a new class path for JAVA_HOME
Step 5: Enter the Variable name as JAVA_HOME and the value to your jdk bin path ie c:ProgramfilesJavajdk-1.6bin and
NOTE Make sure u start with .;
in the Value so that it doesn’t corrupt the other environment variables which is already set.
Step 6 : Follow the Above step and edit the Path in System Variables add the following ;c:ProgramfilesJavajdk-1.6bin
in the value column.
Step 7 :Your are done setting up your environment variables for your Java , In order to test it go to command prompt and type
java
who will get a list of help doc
In order make sure whether compiler is setup Type in cmd
javac
who will get a list related to javac
Hope this Helps !
Taylor Hx
2,80523 silver badges36 bronze badges
answered Nov 4, 2009 at 9:08
Srinivas M.V.Srinivas M.V.
6,4985 gold badges32 silver badges49 bronze badges
6
— To set java path —
There are two ways to set java path
A. Temporary
- Open cmd
- Write in cmd :
javac
If java is not installed, then you will see message:
javac is not recognized as internal or external command, operable program or batch file.
- Write in cmd :
set path=C:Program FilesJavajdk1.8.0_121bin
- Write in cmd :
javac
You can check that path is set if not error has been raised.
It is important to note that these changes are only temporary from programs launched from this cmd.
NOTE: You might have to run the command line as admin
B. Permanent
- Righ-click on «My computer» and click on properties
- Click on «Advanced system settings»
- Click on «Environment variables»
- Click on new tab of user variable
- Write
path
invariable name
- Copy the path of bin folder
- Paste the path of the bin folder in the
variable value
- Click OK
The path is now set permanently.
TIP: The tool «Rapid Environment Editor» (freeware) is great for modifying the environment variables and useful in that case
TIP2: There is also a faster way to access the Environment Variables: press Win+R keys, paste the following %windir%System32rundll32.exe sysdm.cpl,EditEnvironmentVariables
and press ENTER
answered Mar 20, 2017 at 7:04
0
In Windows 7, right-click on Computer -> Properties -> Advanced system settings; then in the Advanced tab, click Environment Variables… -> System variables -> New….
Give the new system variable the name JAVA_HOME
and the value C:Program FilesJavajdk1.7.0_79
(depending on your JDK installation path it varies).
Then select the Path
system variable and click Edit…. Keep the variable name as Path
, and append C:Program FilesJavajdk1.7.0_79bin;
or %JAVA_HOME%bin;
(both mean the same) to the variable value.
Once you are done with above changes, try below steps. If you don’t see similar results, restart the computer and try again. If it still doesn’t work you may need to reinstall JDK.
Open a Windows command prompt (Windows key + R -> enter cmd
-> OK), and check the following:
java -version
You will see something like this:
java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)
Then check the following:
javac -version
You will see something like this:
javac 1.7.0_79
answered Nov 4, 2015 at 3:43
ArunArun
2,3125 gold badges24 silver badges33 bronze badges
The JDK installation instructions explain exactly how to set the PATH
, for different versions of Windows.
Normally you should not set the CLASSPATH
environment variable. If you leave it unset, Java will look in the current directory to find classes. You can use the -cp
or -classpath
command line switch with java
or javac
.
answered Nov 4, 2009 at 8:26
JesperJesper
202k46 gold badges316 silver badges348 bronze badges
1
I am going to explain here by pictures for Windows 7.
Please follow the following steps:
Step 1:
Go to «Start» and get into the «My Computer» properties
Step 2: Go to «Advance System Setting» and click on it.
Step 3: Go to «Start» and get into the «My Computer» properties
Step 4: The dialog for Environment variable will open like this:
Step 5: Go to path and click on edit.
Step 6: Put the path of your JDK wherever it resides up to bin like you can see in the picture. Also add path from your sdk of Android up to the Platform Tools:
answered Jul 10, 2015 at 12:10
hitesh141hitesh141
94912 silver badges25 bronze badges
In programming context you can execute SET command (SET classpath=c:java) or Right click on your computer > properties > advanced > environment variables.
In a batch file you can use
SET classpath=c:java
java c:myapplication.class
answered Nov 4, 2009 at 8:03
Cem KalyoncuCem Kalyoncu
14.1k4 gold badges40 silver badges62 bronze badges
1
For Windows 7 users:
Right-click on My Computer, select Properties; Advanced; System Settings; Advanced; Environment Variables. Then find PATH in the second box and set the variable like in the picture below.
answered May 26, 2014 at 7:56
Zar E AhmerZar E Ahmer
33.7k20 gold badges233 silver badges296 bronze badges
Java path set for java 11
- copy the path for jdk-11
Don’t include the bin folder, just the JDK path. For example
Correct – C:Program FilesJavajdk-11
Wrong – C:Program FilesJavajdk-11bin
In environmental variable, user variable
section click on New button and give path like below.
after that give ok for it and go to the System variables
and select the Path
and double click on it.
click on new and paste %JAVA_HOME%bin
and click ok to all.
answered May 6, 2021 at 22:10
Set java Environment variable in Centos / Linux
/home/ vi .bashrc
export JAVA_HOME=/opt/oracle/product/java/jdk1.8.0_45
export PATH=$JAVA_HOME/bin:$PATH
java -version
answered Aug 9, 2016 at 4:42
0
Keep in mind that the %CLASSPATH%
environment variable is ignored when you use java/javac in combination with one of the -cp
, -classpath
or -jar
arguments. It is also ignored in an IDE like Netbeans/Eclipse/IntelliJ/etc. It is only been used when you use java/javac without any of the above mentioned arguments.
In case of JAR files, the classpath is to be defined as class-path
entry in the manifest.mf file. It can be defined semicolon separated and relative to the JAR file’s root.
In case of an IDE, you have the so-called ‘build path’ which is basically the classpath which is used at both compiletime and runtime. To add external libraries you usually drop the JAR file in a (either precreated by IDE or custom created) lib
folder of the project which is added to the project’s build path.
Vishal Yadav
3,6323 gold badges25 silver badges42 bronze badges
answered Nov 4, 2009 at 11:54
BalusCBalusC
1.1m371 gold badges3602 silver badges3547 bronze badges
2
For deployment better to set up classpath exactly and keep environment clear.
Or at *.bat (the same for linux, but with correct variables symbols):
CLASSPATH="c:lib;d:temptest.jar;<long classpath>"
CLASSPATH=%CLASSPATH%;"<another_logical_droup_of_classpath"
java -cp %CLASSPATH% com.test.MainCLass
Or at command line or *.bat (for *.sh too) if classpath id not very long:
java -cp "c:lib;d:temptest.jar;<short classpath>"
answered Nov 4, 2009 at 8:26
St.ShadowSt.Shadow
1,8401 gold badge12 silver badges16 bronze badges
For Windows:
- Right click on ‘My Computers’ and open ‘Properties’.
- In Windows Vista or Windows 7, go to «Advanced System Settings». Else go to next step.
- Go to ‘Advanced Tab’ and click on Environment Variables button.
- Select ‘Path’ under the list of ‘System Variables’, and press Edit and add
C:Program Filesjavajdkbin
after a semicolon. - Now click on ‘new’ button under system variables and enter ‘JAVA_HOME’ as variable name and path to jdk home directory (ex. ‘C:Program FilesJavajdk1.6.0_24’ if you are installing java version 6. Directory name may change with diff. java versions) as variable_value.
answered Sep 6, 2013 at 11:14
Pratap SinghPratap Singh
4,5871 gold badge22 silver badges24 bronze badges
- Download the JDK
- Install it
- Then Setup environment variables like this :
- Click on EDIT
- Then click PATH, Click Add , Then Add it like this:
answered May 16, 2019 at 11:04
Your Keytools file sit under «Java/bin» folder so you need to either set Environment variable or go to «Java/bin» folder and run command
answered Aug 9, 2021 at 17:35
vaquar khanvaquar khan
10.7k5 gold badges72 silver badges94 bronze badges
You can add JAVA_HOME in the system environment variable from my computer>>advance tab>add the new path as explained here.
It might help Mac and Linux users as well.
answered Jun 12, 2022 at 5:14
SunilSunil
3,1713 gold badges20 silver badges21 bronze badges
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
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 setting the path for both Windows and Linux:
Setting Java Path in Windows
1. Go to the Search box and type advanced system settings in it. Now click on the View advanced system settings.
2. Select the Advanced tab and then click environment variables.
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 FilesJavajdk1.8.0_60.
4. Now in the system variables go to the path and click the edit button.
5. Click the New button.
6. Now add the following path: %JAVA_HOME%bin
Setting 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.
Last Updated :
08 Sep, 2022
Like Article
Save Article
I needed to update my openJDK to 8 version… And I downloaded the new one this way:
sudo add-apt-repository ppa:openjdk-r/ppa
sudo apt-get update
sudo apt-get install openjdk-8-jdk
sudo update-alternatives --config java
sudo update-alternatives --config javac
When I check the Java version
java -version
I get
openjdk version "1.8.0_91"
OpenJDK Runtime Environment (build 1.8.0_91-8u91-b14-0ubuntu4~14.04-b14)
OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)
But where was it saved? I need to know because I should set this path into AndroidStudio
.
Greenonline
2,0108 gold badges20 silver badges27 bronze badges
asked May 14, 2016 at 10:29
Simply do (in terminal):
update-alternatives --list java
And you’ll get an output like this:
$ update-alternatives --list java
/usr/bin/gij-5
/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
The last line is the place your java
is in.
answered May 14, 2016 at 10:38
VideonauthVideonauth
32.9k16 gold badges104 silver badges119 bronze badges
You need to dig into symbolic links. Below is steps to get Java directory
Step 1:
$ whereis java
java: /usr/bin/java /etc/java /usr/share/java
That tells the command java resides in /usr/bin/java.
Step 2:
$ ls -l /usr/bin/java
lrwxrwxrwx 1 root root 22 2009-01-15 18:34 /usr/bin/java -> /etc/alternatives/java
So, now we know that /usr/bin/java
is actually a symbolic link to /etc/alternatives/java
.
Dig deeper using the same method above:
Step 3:
$ ls -l /etc/alternatives/java
lrwxrwxrwx 1 root root 31 2009-01-15 18:34 /etc/alternatives/java -> /usr/local/jre1.6.0_07/bin/java
So, thats the actual location of java: /usr/local/jre.....
You could still dig deeper to find other symbolic links.
Reference : where is java’s home dir?
answered May 14, 2016 at 10:32
SinscarySinscary
1,3759 silver badges27 bronze badges
0
export JAVA_HOME=$(dirname $(dirname $(update-alternatives --list javac)))
To make this seemingly over done setting clearer, on my Ubuntu linux machine with open JDK 8 installed:
$ update-alternatives --list java
/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java
$ update-alternatives --list javac
/usr/lib/jvm/java-8-openjdk-amd64/bin/javac
but what we need is the path to the directory containing bin of the JDK. So ask for the location of javac and then use dirname twice.
See man update-alternatives for more.
answered Apr 28, 2018 at 17:13
1
Starting from January 2019, the licensing model for Oracle Java has changed. PPAs such as ‘ppa:webupd8team/java’ used in many Java installation tutorials now become unavailable.
Here I would like to share how I installed Java 8 on Ubuntu 16.04, and set the Java path in terminal.
Installation
Reference: https://java.com/en/download/help/linux_x64_install.xml
I followed the instruction on the official documentation to install Java with .tar.gz
Path setting
Reference: https://java.com/en/download/help/path.xml
The instruction is also from the official documentations. The steps to set up Java path are much simpler here.
After performing all the steps, restart the terminal and run ‘java -version’ to verify installation.
answered Aug 15, 2019 at 3:03
- Найдите местоположение Java с помощью команды
where java
- Найдите местоположение Java с помощью команды
set JAVA_HOME
- Найдите местоположение Java с помощью команды
dir /b /s java.exe
- Найдите местоположение Java с помощью команды
gcm -All java
в Windows PowerShell
Сегодня мы увидим, как узнать, где находится Java в Windows. Для этого есть несколько способов и команд; мы проверим различные команды, которые возвращают окна местоположения Java.
Найдите местоположение Java с помощью команды where java
Наиболее часто используемая команда для получения текущего местоположения Java в Windows — это where java
. Это команда Windows, которая работает так же, как команда whereis
в операционной системе Linux. Команда where
используется для отображения местоположения исполняемого файла. Обычно используется шаблон поиска.
Как показано ниже, когда мы запускаем команду where java
в командной строке Windows, она возвращает местоположение java.exe
.
Выход:
C:User.jdksopenjdk-15.0.1binjava.exe
Найдите местоположение Java с помощью команды set JAVA_HOME
Следующий способ узнать местоположение Java в Windows — использовать команду установить JAVA_HOME
. В Windows путь к Java или JDK хранится в переменных среды. Местоположение хранится в переменной с именем PATH
, списке каталогов, которые можно использовать для прямого доступа к определенным программам, таким как Java, без записи всего пути.
Мы можем установить путь к Java командой set JAVA_HOME
, а затем указать путь. Но если значение уже установлено, он вернет путь, установленный к переменной JAVA_HOME
. Это завершает нашу задачу, поскольку это каталог, в котором находится Java.
C:UsersRupam Saini>set JAVA_HOME
Выход:
JAVA_HOME=C:UsersRupam Saini.jdksopenjdk-15.0.1
Найдите местоположение Java с помощью команды dir /b /s java.exe
Команда dir
показывает все папки и подпапки в текущем местоположении. Мы можем использовать эту команду для получения местоположения Java, поскольку на одном компьютере с Windows может быть более одного исполняемого файла Java, поскольку некоторые программы используют свою собственную среду Java.
Мы используем команду dir
с тремя параметрами, первым из которых является /b
, который отображает только путь к каталогу без каких-либо дополнительных деталей. Напротив, параметр /s
перечисляет все вхождения указанного файла в текущем каталоге и подкаталогах и, наконец, имя выполнения java.exe
.
C:User>dir /b /s java.exe
Выход:
C:User.jdksopenjdk-15.0.1binjava.exe
C:UserAppDataLocalJetBrainsIntelliJ IDEA Community Edition 2020.3jbrbinjava.exe
Найдите местоположение Java с помощью команды gcm -All java
в Windows PowerShell
Во всех примерах в этом руководстве мы используем традиционную командную строку, но для этого метода требуется Windows PowerShell, командная строка, но с расширенными возможностями. В PowerShell мы используем команду gcm
, сокращенно от get-command
. Он возвращает все команды в машине.
Мы используем gcm
с двумя параметрами; первый — -All
, который показывает все экземпляры команды на текущей машине, а второй параметр — это имя команды. В нашем случае имя команды java
. В свою очередь, он выводит некоторые сведения о команде, такие как тип команды, имя исполняемого файла, выполняемого по команде, версия и источник исполняемого файла. Источник — это место, где находится Java.
PS C:User> gcm -All java
Выход:
CommandType Name Version Source
----------- ---- ------- ------
Application java.exe 15.0.1.0 C:User.jdksopenjdk-15...