Не работает javac в консоли windows 10

I'm trying to use javac with the windows command prompt, but it's not working. After adding the directory "C:Program FilesJavajdk1.6.0_16bin" to the end of the PATH environment variable, the ...

I’m trying to use javac with the windows command prompt, but it’s not working.

After adding the directory "C:Program FilesJavajdk1.6.0_16bin" to the end of the PATH environment variable, the java command works fine, but using javac gives me the following error:

‘javac’ is not recognized as an internal or external command, operable program or batch file.

Micha Wiedenmann's user avatar

asked Nov 5, 2009 at 5:26

Dom M.'s user avatar

1

If you added it in the control panel while your command prompt was open, that won’t affect your current command prompt. You’ll need to exit and re-open or simply do:

set "path=%path%;c:program filesjavajdk1.6.0_16bin"

By way of checking, execute:

echo %path%

from your command prompt and let us know what it is.

Otherwise, make sure there is a javac in that directory by trying:

"c:program filesjavajdk1.6.0_16binjavac.exe"

from the command prompt. You can also tell which executable (if any) is being used with the command:

for %i in (javac.exe) do @echo %~$PATH:i

This is a neat trick similar to the which and/or whence commands in some UNIX-type operating systems.

answered Nov 5, 2009 at 5:29

paxdiablo's user avatar

paxdiablopaxdiablo

838k230 gold badges1561 silver badges1929 bronze badges

5

Windows OS searches the current directory and the directories listed in the PATH environment variable for executable programs. JDK’s programs (such as Java compiler javac.exe and Java runtime java.exe) reside in directory «bin» (where denotes the JDK installed directory, e.g., C:Program FilesJavajdk1.8.0_xx). You need to include the «bin» directory in the PATH.

To edit the PATH environment variable in Windows XP/Vista/7/8:

  1. Control Panel ⇒ System ⇒ Advanced system settings

  2. Switch to «Advanced» tab ⇒ Environment Variables

  3. In «System Variables», scroll down to select «PATH» ⇒ Edit

(( now read the following 3 times before proceeding, THERE IS NO UNDO ))

In «Variable value» field, INSERT «c:Program FilesJavajdk1.8.0_xxbin» (Replace xx with the upgrade number and VERIFY that this is your JDK’s binary directory!!!) IN FRONT of all the existing directories, followed by a semi-colon (;) which separates the JDK’s binary directory from the rest of the existing directories.
DO NOT DELETE any existing entries; otherwise, some existing applications may not run.

Variable name  : PATH
Variable value : c:Program FilesJavajdk1.8.0_xxbin;[existing entries...]

Screenshot

answered Apr 6, 2012 at 17:07

mike's user avatar

mikemike

8716 silver badges2 bronze badges

4

After a long Google, I came to know that javac.exe will be inside JDK(C:Program FilesJavajdk(version number)bin) not inside JRE (C:Program Files (x86)Javajre7bin) «JRE doesn’t come with a compiler. It(JRE) is simply a java runtime environment. What you need is the Java development kit.» in order to use compiler javac

javac will not work if the path points to bin inside jre folder

In order to use javac in cmd , JDK must be installed in your system…

For javac path

path = C:Program Files (x86)Javajre7bin this is wrong

path = C:Program FilesJavajdk(version number)bin this is correct

Make sure that «javac.exe» is inside your «C:Program FilesJavajdk(version number)bin»

Don’t get confused with JRE and JDK both are totally different

if you don’t have JDK pls download from this link

https://jdk.java.net/

or

http://www.oracle.com/technetwork/java/javase/downloads/index.html

reference thread for JDK VS JRE What is the difference between JDK and JRE?

answered Dec 31, 2013 at 15:06

TechDog's user avatar

TechDogTechDog

2,9891 gold badge25 silver badges29 bronze badges

0

I know this may not be your specific error, but I once had a leading space in my path and java would work but javac would not.

For what it’s worth, I offer the sage advice: «Examine your Path closely».

answered Apr 3, 2012 at 10:31

Sam's user avatar

SamSam

8212 gold badges8 silver badges16 bronze badges

Okay this can not be the case always but many of us have done this mistake in the past and few out of those are still not aware of it, which is, every time you append a path (any path) of any environment variable, you’re likely to hit the space bar right after the «semicolon» (as you normally would, after the «period» while typing in an editor).

This will create a leading space in the path e.g » C:Program FilesJavajdk1.6.0bin» and therefore «javac.exe» won’t be found by the system.

answered Aug 3, 2013 at 7:32

Malay Desai's user avatar

Malay DesaiMalay Desai

5185 silver badges6 bronze badges

0

Try the solutions here: http://techdem.centerkey.com/2009/05/javahome-command-script.html

These are much more robust to change — like when you upgrade the JDK or JRE, since there is no hard coded path.

The quick solution (if you don’t want to read the blog) is

C:>for /d %i in ("Program FilesJavajdk*") do set JAVA_HOME=%i
C:>set PATH=%PATH%;%JAVA_HOME%

You can then add these lines to a startup/login script.

answered Nov 4, 2013 at 15:10

Jason's user avatar

JasonJason

11.4k9 gold badges62 silver badges82 bronze badges

1

I just had to do this to get this to work on windows 7 64.

Open up a command prompt (cmd.exe) and type:

set CLASSPATH=C:Program FilesJavajdk1.7.0_01bin

Make sure you reopen all running command prompt Windows to get the environment variable updated as well.

eckes's user avatar

eckes

10k1 gold badge58 silver badges71 bronze badges

answered Nov 16, 2011 at 3:10

Ryan Summey's user avatar

1

Change the folder «jdk1.7.0_45» «jdk1_7_0_60» and update the path in Windows environment. Otherwise, the path ignores the dot at the front which stands for hidden file and so the folder is not displayed in PATH strings.

answered Jun 13, 2014 at 3:21

NewDev's user avatar

«;C:Program FilesJavajdk1.6.0bin» sometime you may forget to put semicolon on last existing path.

answered May 9, 2013 at 15:48

Sundararajan wasuvan's user avatar

I faced the exact same problem that java would work but javac would not on a cmd prompt in Windows 8.

The problem occured because I forgot to remove '>' at the end of the path name, i.e., it was like this:

C:Program FilesJavajdk*bin>

where it was suppose to be like this:

C:Program FilesJavajdk*bin

Joël Salamin's user avatar

Joël Salamin

3,5183 gold badges21 silver badges33 bronze badges

answered Sep 15, 2014 at 11:24

Kevin's user avatar

The path will only be set for the administrator account. Therefore it is important to launch command prompt as administrator, if you are not already.

answered Jan 8, 2015 at 15:02

Ensure you don’t allow spaces (white space) in between paths in the Path variable. My problem was I had white space in and I believe Windows treated it as a NULL and didn’t read my path in for Java.

TResponse's user avatar

TResponse

3,8907 gold badges45 silver badges63 bronze badges

answered Jan 27, 2015 at 2:05

TRHUMMEL's user avatar

I was having the same problem posted in this title. Java would work, but javac would not in the Windows command prompt (cmd.exe).

For me, it was simply that I had placed a space when adding C:Program FilesJavajdk1.8.0bin to the end of my %PATH% environment variable.
Remove the space between the ; and the next file path.

Siguza's user avatar

Siguza

19.7k6 gold badges51 silver badges81 bronze badges

answered Mar 31, 2014 at 15:49

Taiton's user avatar

I appreciate this is an old question now but my solution wasn’t an answer on here so posting it in case anyone else tries all the rest.

In my case, a previous install of the Java JRE (in ProgramData/Oracle/Java) had a path variable at the top of my list of path variables. The contents of that «Oracle» path had a java.exe but not a javac.exe.
I added my full JDK path to the top of the list of path variables, ahead of the «Oracle» one, and it then picked up javac.exe as well as java.

answered Sep 27, 2016 at 22:10

Neil's user avatar

NeilNeil

4034 silver badges22 bronze badges

for /d %i in ("Program FilesJavajdk*") do set JAVA_HOME=%i
set JAVA_HOME

this solution worked to me

answered Sep 2, 2017 at 6:45

Cristian Agudelo's user avatar

1

When i tried to make the .java to .class the command Javac didnt work. I got it working by going to C:Program Files (x86)Javajdk1.7.0_04bin and when i was on that directory I typed Javac.exe CTesttest.java and it made the class with that tactic. Try that out.

answered Jun 12, 2012 at 9:47

Someone's user avatar

Give it as «C:Program FilesJavajdk1.6.0_16bin». Remove the backslash it will work

answered Nov 5, 2009 at 5:31

valli's user avatar

vallivalli

5,6872 gold badges19 silver badges9 bronze badges

1

I’m trying to use javac with the windows command prompt, but it’s not working.

After adding the directory "C:Program FilesJavajdk1.6.0_16bin" to the end of the PATH environment variable, the java command works fine, but using javac gives me the following error:

‘javac’ is not recognized as an internal or external command, operable program or batch file.

Micha Wiedenmann's user avatar

asked Nov 5, 2009 at 5:26

Dom M.'s user avatar

1

If you added it in the control panel while your command prompt was open, that won’t affect your current command prompt. You’ll need to exit and re-open or simply do:

set "path=%path%;c:program filesjavajdk1.6.0_16bin"

By way of checking, execute:

echo %path%

from your command prompt and let us know what it is.

Otherwise, make sure there is a javac in that directory by trying:

"c:program filesjavajdk1.6.0_16binjavac.exe"

from the command prompt. You can also tell which executable (if any) is being used with the command:

for %i in (javac.exe) do @echo %~$PATH:i

This is a neat trick similar to the which and/or whence commands in some UNIX-type operating systems.

answered Nov 5, 2009 at 5:29

paxdiablo's user avatar

paxdiablopaxdiablo

838k230 gold badges1561 silver badges1929 bronze badges

5

Windows OS searches the current directory and the directories listed in the PATH environment variable for executable programs. JDK’s programs (such as Java compiler javac.exe and Java runtime java.exe) reside in directory «bin» (where denotes the JDK installed directory, e.g., C:Program FilesJavajdk1.8.0_xx). You need to include the «bin» directory in the PATH.

To edit the PATH environment variable in Windows XP/Vista/7/8:

  1. Control Panel ⇒ System ⇒ Advanced system settings

  2. Switch to «Advanced» tab ⇒ Environment Variables

  3. In «System Variables», scroll down to select «PATH» ⇒ Edit

(( now read the following 3 times before proceeding, THERE IS NO UNDO ))

In «Variable value» field, INSERT «c:Program FilesJavajdk1.8.0_xxbin» (Replace xx with the upgrade number and VERIFY that this is your JDK’s binary directory!!!) IN FRONT of all the existing directories, followed by a semi-colon (;) which separates the JDK’s binary directory from the rest of the existing directories.
DO NOT DELETE any existing entries; otherwise, some existing applications may not run.

Variable name  : PATH
Variable value : c:Program FilesJavajdk1.8.0_xxbin;[existing entries...]

Screenshot

answered Apr 6, 2012 at 17:07

mike's user avatar

mikemike

8716 silver badges2 bronze badges

4

After a long Google, I came to know that javac.exe will be inside JDK(C:Program FilesJavajdk(version number)bin) not inside JRE (C:Program Files (x86)Javajre7bin) «JRE doesn’t come with a compiler. It(JRE) is simply a java runtime environment. What you need is the Java development kit.» in order to use compiler javac

javac will not work if the path points to bin inside jre folder

In order to use javac in cmd , JDK must be installed in your system…

For javac path

path = C:Program Files (x86)Javajre7bin this is wrong

path = C:Program FilesJavajdk(version number)bin this is correct

Make sure that «javac.exe» is inside your «C:Program FilesJavajdk(version number)bin»

Don’t get confused with JRE and JDK both are totally different

if you don’t have JDK pls download from this link

https://jdk.java.net/

or

http://www.oracle.com/technetwork/java/javase/downloads/index.html

reference thread for JDK VS JRE What is the difference between JDK and JRE?

answered Dec 31, 2013 at 15:06

TechDog's user avatar

TechDogTechDog

2,9891 gold badge25 silver badges29 bronze badges

0

I know this may not be your specific error, but I once had a leading space in my path and java would work but javac would not.

For what it’s worth, I offer the sage advice: «Examine your Path closely».

answered Apr 3, 2012 at 10:31

Sam's user avatar

SamSam

8212 gold badges8 silver badges16 bronze badges

Okay this can not be the case always but many of us have done this mistake in the past and few out of those are still not aware of it, which is, every time you append a path (any path) of any environment variable, you’re likely to hit the space bar right after the «semicolon» (as you normally would, after the «period» while typing in an editor).

This will create a leading space in the path e.g » C:Program FilesJavajdk1.6.0bin» and therefore «javac.exe» won’t be found by the system.

answered Aug 3, 2013 at 7:32

Malay Desai's user avatar

Malay DesaiMalay Desai

5185 silver badges6 bronze badges

0

Try the solutions here: http://techdem.centerkey.com/2009/05/javahome-command-script.html

These are much more robust to change — like when you upgrade the JDK or JRE, since there is no hard coded path.

The quick solution (if you don’t want to read the blog) is

C:>for /d %i in ("Program FilesJavajdk*") do set JAVA_HOME=%i
C:>set PATH=%PATH%;%JAVA_HOME%

You can then add these lines to a startup/login script.

answered Nov 4, 2013 at 15:10

Jason's user avatar

JasonJason

11.4k9 gold badges62 silver badges82 bronze badges

1

I just had to do this to get this to work on windows 7 64.

Open up a command prompt (cmd.exe) and type:

set CLASSPATH=C:Program FilesJavajdk1.7.0_01bin

Make sure you reopen all running command prompt Windows to get the environment variable updated as well.

eckes's user avatar

eckes

10k1 gold badge58 silver badges71 bronze badges

answered Nov 16, 2011 at 3:10

Ryan Summey's user avatar

1

Change the folder «jdk1.7.0_45» «jdk1_7_0_60» and update the path in Windows environment. Otherwise, the path ignores the dot at the front which stands for hidden file and so the folder is not displayed in PATH strings.

answered Jun 13, 2014 at 3:21

NewDev's user avatar

«;C:Program FilesJavajdk1.6.0bin» sometime you may forget to put semicolon on last existing path.

answered May 9, 2013 at 15:48

Sundararajan wasuvan's user avatar

I faced the exact same problem that java would work but javac would not on a cmd prompt in Windows 8.

The problem occured because I forgot to remove '>' at the end of the path name, i.e., it was like this:

C:Program FilesJavajdk*bin>

where it was suppose to be like this:

C:Program FilesJavajdk*bin

Joël Salamin's user avatar

Joël Salamin

3,5183 gold badges21 silver badges33 bronze badges

answered Sep 15, 2014 at 11:24

Kevin's user avatar

The path will only be set for the administrator account. Therefore it is important to launch command prompt as administrator, if you are not already.

answered Jan 8, 2015 at 15:02

Ensure you don’t allow spaces (white space) in between paths in the Path variable. My problem was I had white space in and I believe Windows treated it as a NULL and didn’t read my path in for Java.

TResponse's user avatar

TResponse

3,8907 gold badges45 silver badges63 bronze badges

answered Jan 27, 2015 at 2:05

TRHUMMEL's user avatar

I was having the same problem posted in this title. Java would work, but javac would not in the Windows command prompt (cmd.exe).

For me, it was simply that I had placed a space when adding C:Program FilesJavajdk1.8.0bin to the end of my %PATH% environment variable.
Remove the space between the ; and the next file path.

Siguza's user avatar

Siguza

19.7k6 gold badges51 silver badges81 bronze badges

answered Mar 31, 2014 at 15:49

Taiton's user avatar

I appreciate this is an old question now but my solution wasn’t an answer on here so posting it in case anyone else tries all the rest.

In my case, a previous install of the Java JRE (in ProgramData/Oracle/Java) had a path variable at the top of my list of path variables. The contents of that «Oracle» path had a java.exe but not a javac.exe.
I added my full JDK path to the top of the list of path variables, ahead of the «Oracle» one, and it then picked up javac.exe as well as java.

answered Sep 27, 2016 at 22:10

Neil's user avatar

NeilNeil

4034 silver badges22 bronze badges

for /d %i in ("Program FilesJavajdk*") do set JAVA_HOME=%i
set JAVA_HOME

this solution worked to me

answered Sep 2, 2017 at 6:45

Cristian Agudelo's user avatar

1

When i tried to make the .java to .class the command Javac didnt work. I got it working by going to C:Program Files (x86)Javajdk1.7.0_04bin and when i was on that directory I typed Javac.exe CTesttest.java and it made the class with that tactic. Try that out.

answered Jun 12, 2012 at 9:47

Someone's user avatar

Give it as «C:Program FilesJavajdk1.6.0_16bin». Remove the backslash it will work

answered Nov 5, 2009 at 5:31

valli's user avatar

vallivalli

5,6872 gold badges19 silver badges9 bronze badges

1

the problem is that I upgraded to Windows 10 and now I’m installing my tools to programming and now that I installed the JDK 7 of Java, when I try to use in the cmd the command:
— «javac»

The result of this is: «javac» is not recognized as an internal or external command…

But I was edited the PATH with the correct link of jdk, because when I use «java», it is ok.

Now, I tried in the console with this command: PATH=%PATH%;"C:Program FilesJavajdk1.7.0_79bin"

And when I executed the command «javac» it works, but now, when I open other console, it doesn’t work, or when I restart the console, this command is not recognized.

What could be the problem?

Bogota's user avatar

Bogota

4014 silver badges15 bronze badges

asked Aug 10, 2015 at 17:15

Sadôk's user avatar

3

java is part of the JRE, not the JDK.

You need to add the JDK bin to the system PATH, in

«Control Panel» | System | Advanced | «Environment Variables»

xenteros's user avatar

xenteros

15.4k12 gold badges54 silver badges89 bronze badges

answered Aug 10, 2015 at 17:17

SLaks's user avatar

SLaksSLaks

857k175 gold badges1886 silver badges1956 bronze badges

4

Her’s how I configure System variable on Windows 10 :

enter image description here

David Arenburg's user avatar

answered Apr 1, 2016 at 10:50

Mahesh Sonavane's user avatar

I am totally new to java and spent hours trying to get the problems with PATH and CLASSPATH worked out. There was one person who said to restart the command prompt after you modify the environment variables; that was it for me. While you are testing different configurations, make sure to relaunch the command prompt before testing. It seems like there are at least 2 different ways of setting this up. I went with the following:

1) In System Variables, add

JAVA_HOME = c:program files (x86)javajdk1.8.0_121

2) In System Variables, add the following to existing Path…

%JAVA_HOME%bin

That’s it.
No need for quotes around anything. No double forward slashes or anything else. I think it would also work if I removed the java_home variable and just listed the explicit path to bin in the PATH variable, but I’m not touching it again now that it finally works.

Amit Phaltankar's user avatar

answered Jun 22, 2017 at 0:16

justaguy's user avatar

justaguyjustaguy

1011 silver badge2 bronze badges

1

After adding C:Program FilesJavajdk1.8.0_73bin to the system variables I turned off my command prompt and opened another one. Then it worked.

answered Oct 23, 2016 at 17:34

V.P.'s user avatar

V.P.V.P.

911 silver badge1 bronze badge

1

Maybe a bit late, but i had same problem.

Click on «Move up» button for Java path and move it at top.

It fixed problem for me

answered Dec 6, 2015 at 8:43

Crispy's user avatar

CrispyCrispy

611 silver badge1 bronze badge

2

just add C:Program FilesJavajdk1.7.0_80bin as the path in environmental variables. no need to add java.exe and javac.exe to that path. IT WORKS

answered Feb 16, 2016 at 3:31

Sreeni's user avatar

SreeniSreeni

751 silver badge10 bronze badges

I added below Path in environment variable

;%JAVA_HOME%/bin instead of %JAVA_HOME%bin

in my case , it fix the problem

answered Jun 16, 2016 at 13:08

troh's user avatar

0

I had the same issue on Windows 10 — the java -version command was working but javac -version was not. There are three things I did:

(1) I downloaded the latest jdk (not the jre) and installed it. Then, I added the jdk/bin path tan o environment variable. In my case, it was C:Program FilesJavajdk-10bin. I did not need to add the ; for Windows 10.

(2) Move this path to the top of all the other paths.

(3) Delete any other Java paths that might exist.

Test the java -version and javac -version commands again. Voila!

answered Apr 1, 2018 at 19:51

Manan Gupta's user avatar

0

For some reason it worked for me to add quotation marks to the path folder on windows 10. not C:Program FilesJavajdk 1.8.0_111bin, but «C:Program FilesJavajdk 1.8.0_111bin».

answered Oct 21, 2016 at 0:06

Mściwój Ogórkowski's user avatar

now i got it finally! make sure that there are no spaces before and after the path and put the semi-colon on both sides without spaces

answered Nov 30, 2016 at 12:30

Yazan Al-Hinnawi's user avatar

The PATH is for current user, instead you can add a CLASSPATH and below link would help you more PATH and CLASSPATH

answered Aug 10, 2015 at 17:21

ihappyk's user avatar

ihappykihappyk

5151 gold badge5 silver badges16 bronze badges

2

I added below Path in environment variable

C:Program FilesJavajdk1.8.0_91bin

and then compiled the program but got the error then I restarted the system and again compiled the program

This time it worked :)

answered Jun 2, 2016 at 22:30

Ram kaatiya's user avatar

Add java path to environment variables and move it to the top of all the paths available there. It worked for me.

answered Mar 5, 2017 at 11:57

yoshitha's user avatar

To be sure about your path, you can use double quotes " to locate the path or if you are in Windows, you can browse to path to select "C:Program FilesJavajdk1.8.0_121bin" folder.

jediz's user avatar

jediz

4,3775 gold badges34 silver badges41 bronze badges

answered May 9, 2017 at 15:03

Sanjoy Paul's user avatar

in the search window type ‘environment variables’ this should give you a link to editing the variables. On the variables editing page there is an upper section and a lower section in the lower section add NEW,type path C:Program FilesJavajdk-10bin this worked great for me and it finds the compiler all the time.

answered Apr 4, 2018 at 17:58

mcchud's user avatar

Kind of beating a dead horse now but, I want to clarify one thing that may not be quite so obvious. Yes indeed you need to edit the PATH environment variable as already stated many times. The key for me was to edit the PATH under SYSTEM variables. I had inadvertently edited the PATH under USER variables. Why did this matter? On my machine I have to log in as an Administrator to edit environment variables. So editing the User variables was not helping because I run the command prompt under my login (non-admin) account. Grrr!

Also, I found that closing the command prompt window, and re-opening it after the PATH variable update was required. Changing the order of the values, adding semi-colons, etc. didn’t make a difference for me.

Cheers

answered Jun 20, 2018 at 1:42

Daniel Knowlton's user avatar

If you have set all PATH variables correctly after installation, just restart it.

I had the same problem, I had also installed new Windows7 OS then I upgraded it to Win 10. Then i started setup necessary tools like IntelliJ, Java jdk,jre, eclipse so on.
In cmd, java -version worked but javac compiler got unrecognized. I checked and all good, the files in the folders, path are correct and so on.

I restarted and checked it again in cmd ,it worked.

Reji's user avatar

Reji

3,3362 gold badges21 silver badges25 bronze badges

answered Feb 17, 2020 at 0:30

Kenan Baku's user avatar

what I did is:

I typed ; accidentally in front in the path variable and then hit OK, after this if I again edit it was nowhere going to the same page as earlier, it opened a new page as defined for user variables and then I was able to remove double quotes in front of the PATH VARIABLE.
Everything worked fine then. :)

Did it just now.

answered Jul 21, 2018 at 19:41

y_159's user avatar

y_159y_159

4183 silver badges15 bronze badges

Add

PATH = C:Program FilesJavajdk1.8.0_66bin 

in Advanced system setting. Then Choose Environment Variable.

ksokol's user avatar

ksokol

7,9053 gold badges43 silver badges56 bronze badges

answered Nov 24, 2015 at 10:42

A_Anonymous's user avatar

for windows 10 Users Use Java path( JDK Bin location) AS «C:Program FilesJavajdk-9.0.1bin» it will work.

answered Dec 17, 2017 at 7:47

Ramachandrudu R's user avatar

0

Points to remember, do as the image shows. Move the highlighted bar up using move up button, this will help.

Blue's user avatar

Blue

22.3k7 gold badges57 silver badges89 bronze badges

answered Oct 23, 2018 at 11:27

Aditya Rana's user avatar

1

На чтение 6 мин. Просмотров 174 Опубликовано 19.04.2021

« Javac не распознается как внутренняя или внешняя команда » – ошибка, с которой часто сталкиваются люди, пытающиеся скомпилировать программы Java в Windows с помощью командной строки. С этим также можно столкнуться, когда пользователи пытаются проверить текущую версию основного компилятора Java.

Содержание

  1. Что такое JavaC?
  2. Причина, по которой ошибка Javac не распознается
  3. Шаг 1. Установка Java Development Kit (JDK)
  4. Шаг 2: Установка переменной среды Java и обновление системного пути
  5. Дополнительный шаг: проверка успешности настройки

Что такое JavaC?

Javac (произносится как «java-see»), является основным компилятором Java, включенным в JDK (Java Development Kit) , разработанный корпорацией Oracle. Компилятор предназначен для приема исходного кода, соответствующего спецификациям языка Java (JL) , и преобразования его в байт-код Java в соответствии с JVM (Java Virtual Спецификация машины).

Причина, по которой ошибка Javac не распознается

Ошибка « Javac не распознается как внутренняя или внешняя команда », когда командная строка не может найти переменную Java PATH. Это может произойти по двум причинам:

  • Java Development Kit (JDK) отсутствует на компьютере . Обычно это происходит из-за того, что пользователь по ошибке предполагает, что компилятор Java (javac) установлен вместе с средой выполнения Java .
  • Путь к Javac не задан или указан неверно set – чтобы выполнить компиляцию из командной строки и убедиться, что другие инструменты сервера приложений работают правильно, система должна знать местоположение Javac. В этом случае вам нужно будет указать путь вручную.

Шаг 1. Установка Java Development Kit (JDK)

Одна из основных причин возникновения этой ошибки заключается в том, что пользователи, которые только начинают изучать Java, путают Java Runtime Environment (JRE) с Java Development Kit (JDK) .

JRE является частью JDK , но большая часть время скачивается отдельно. Многие программы, использующие среду выполнения Java, включают ее в свои установочные пакеты.

Поскольку существует очень мало причин, по которым вам понадобится Java Development Kit (JDK), если вы не Если вы заинтересованы в разработке Java, вы могли подумать, что Javac уже установлен JRE, но на самом деле вам нужно будет установить весь Java Development Kit.

Если вы считаете, что этот сценарий применим к вашей ситуации, вот краткое руководство по установке Java Development Kit (JDK) для устранения ошибки «javac не распознается» :

  1. Перейдите по этой ссылке ( здесь ) и щелкните значок Загрузить над Платформа Java (JDK ) . Это обеспечит установку последней доступной версии Java Development Kit ..
  2. На следующем экране прокрутите вниз до Java SE Development Kit и убедитесь, что вы выбрали переключатель, связанный с Принять лицензионное соглашение . Затем щелкните ссылку для загрузки, связанную с Windows. Есть два варианта на выбор, но мы рекомендуем загрузить файл .exe, поскольку он избавит вас от извлечения содержимого после завершения загрузки.
  3. После завершения загрузки откройте исполняемый файл установки JDK и следуйте инструкциям на экране, чтобы завершить установку.
  4. На следующем экране убедитесь, что для установки установлены как Инструменты разработки , так и Исходный код . на локальном жестком диске вместе со всеми их функциями. Кроме того, если возможно, мы рекомендуем вам сохранить путь установки по умолчанию, потому что шаг 2 будет проще.

    Примечание. В качестве дополнительной рекомендации запишите путь установки в разделе «Установить в», поскольку он понадобится вам на шаге 2 .

  5. Дождитесь установки Java Development Kit . Когда процесс будет завершен, перезагрузите компьютер вручную, если вам не будет предложено сделать это автоматически.

Теперь, когда вы убедились, что установили правильный пакет, устанавливающий JavaC, перейдите к шагу 2, где мы убедимся, что вы правильно указали путь к JavaC.

Шаг 2: Установка переменной среды Java и обновление системного пути

Прежде чем мы начнем с этого процесса, важно поймите, что следующие процедуры применимы только в том случае, если вы убедились, что Java Development Kit правильно установлен ( Шаг 1 ).

Если вы установили JDK и все еще получают сообщение « Javac не распознается как внутренняя или внешняя команда », вы только что наткнулись на одну из наиболее распространенных технических проблем, с которыми сталкиваются новички в Java. Чтобы завершить работу над Java Development Kit в Windows, вам необходимо выполнить ряд действий вручную. Эти шаги всегда должны следовать за установкой JDK, даже после обновления комплекта разработки Java.

Вот краткое руководство по установке правильной переменной среды Java и обновлению системного пути:

  1. Нажмите клавишу Windows + R , чтобы открыть диалоговое окно Выполнить . Затем введите « sysdm.cpl » и нажмите Enter , чтобы открыть окно Свойства системы .
  2. В окне Свойства системы перейдите на вкладку Дополнительно и нажмите Среда Переменные .
  3. Во вновь открывшемся окне переменных среды щелкните значок Кнопка Создать под системной переменной .
  4. В окне Новая системная переменная установите для Имя переменной значение JAVA_HOME и значение переменной на путь к вашему каталогу JDK . Чтобы сохранить изменения, нажмите OK.

    если вы прислушались к нашим советам на шаге 1 и записали путь установки JDK, вы можете вставить его прямо в Значение переменной .

  5. Теперь, когда вы v e вернувшись в окно Переменные среды , найдите переменную с именем path в разделе Системные переменные . Выбрав переменную Path , нажмите кнопку Edit .
  6. В окне Изменить переменную среды нажмите кнопку Создать .
  7. Назовите вновь созданную переменную среды % JAVA_HOME% bin и нажмите Enter . Затем нажмите Ok , чтобы применить изменения.
  8. С этим На последнем этапе ваша среда Java должна быть настроена. Теперь вы сможете компилировать приложения из CMD или проверять свою версию Javac.

Дополнительный шаг: проверка успешности настройки

Есть еще один дополнительный шаг, который вы можете выполнить в командной строке, чтобы убедиться, что вы успешно настроил путь к переменной среды Java. Выполните следующие действия, чтобы проверить, работает ли ваша конфигурация:

  1. Нажмите клавишу Windows + R , чтобы открыть диалоговое окно «Выполнить». Затем введите « cmd » и нажмите Enter , чтобы открыть окно командной строки.
  2. В окне командной строки введите echo% JAVA_HOME% и нажмите Enter, чтобы узнать, какой ответ вы получите. Если вы видите распечатку с каталогом для JDK, то шаг 2 был успешным и ваш JAVAC работает нормально. Если вы видите пробел вместо пути JDK, это означает, что вам не удалось настроить переменную среды – в этом случае вернитесь к шагу 1 и шагу 2. .
  • Причина ошибки

  • Исправление

Работая с Java кодом через консоль, может появится ошибка: “javac не является внутренней или внешней командой”. Как ее исправить читайте в этой статье.

Причина ошибки

Причина ошибки – заданы некорректные “переменные среды”. Соответственно, необходимо указать правильные.

Исправление

На рабочем столе откройте “Этот компьютер”:

  1. Нажмите слева вверху “Свойства”, затем слева в меню – “Дополнительные параметры системы”.Система Windows
  2. В открывшейся вкладке “Дополнительно” в самом низу выберите “Переменные среды”.Переменные среды
  3. Откроется содержимое. Нажмите в каждом окне поочередно “Создать”.Переменные среды
  4. В окне “Новая пользовательская переменная” пропишите CLASSPATH.Новая пользовательская переменная
  5. Затем в окне “Новая системная переменная” укажите переменную PATH. В поле “Значение” пропишите директорию к пакету JDK.Новая системная переменная
  6. Перезагрузите Windows.

Кроме того, чтобы выполнить Javac, вы можете в командной строке прописать полный путь к консоли. К примеру:

"C:Program FilesJavajdk1.8.0_102binjavac.exe" MyFile.java

Рекомендую также не забывать про обновления Java. Чтобы их не пропустить, используйте программу Java Update Available.

Javac is not recognized as an internal or external command” is an error often encountered by people trying to compile Java programs on Windows using Command Prompt. It’s might also be encountered when users try to check the current version of the primary Java compiler.

What is JavaC?

Javac (pronounced “java-see”), is the main Java compiler included in the JDK (Java Development Kit) developed by Oracle Corporation. The compiler is designed to accept source code that is conforming with the Java Language specifications (JLs) and converts it into Java bytecode according to the JVMs (Java Virtual Machine Specification).

What causes the Javac is not recognized error

The “Javac is not recognized as an internal or external command” error is encountered when the Command Prompt is unable to find the Java PATH variable. This can happen for two reasons:

  • The Java Development Kit (JDK) is missing from the machine – This typically happens because the user mistakenly assumes that the Java Compiler (javac) is installed along with the Java Runtime Environment.
  • The path to Javac is not set or is incorrectly set – In order to compile from Command Prompt and to make sure that other app server tools function properly, the system needs to be aware of the location of Javac. If this is the case, you will need to set the path manually.

Step 1: Installing the Java Development Kit (JDK)

One of the main reasons why this error occurs is because users that are just starting to learn Java are confusing the Java Runtime Environment (JRE) with the Java Development Kit (JDK).

The JRE is part of the JDK, but most of the time is downloaded separately. A lot of programs that make use of the Java Runtime include it in their installation packages.

Because there are very few reasons why you’ll need the Java Development Kit (JDK) if you’re not interested in Java Development, you might have believed that Javac was already installed by JRE, but the truth is you’ll need to install the whole Java Development Kit.

If you think this scenario is applicable to your situation, here’s a quick guide on installing the Java Development Kit (JDK) in order to resolve the “javac is not recognized” error:

  1. Visit this link (here) and click the Download Icon above Java Platform (JDK). This will ensure that you install the latest available version of the Java Development Kit.Downloading latest JDK
    Downloading latest JDK
  2. In the next screen, scroll down to Java SE Development Kit and make sure that you select the toggle associated with the Accept Licence agreement. Then, click on the download link associated with Windows. There are two options to choose from, but we recommend downloading the .exe file since it will spare you from extracting the contents when the download is complete.Downloading the Java Development Kit
    Downloading the Java Development Kit
  3. Once the download is complete, open the JDK installation executable and follow the on-screen prompts to complete the installation.Installing the Java Development kit
    Installing the Java Development Kit
  4. In the next screen, make sure that both Development Tools and Source Code are set to install on your local hard drive along with all their subfeatures. Furthermore, if possible, we encourage you to preserve the default installation path because Step 2 will be easier.Install all components and subfeatures to your local hard drive
    Install all components and subfeatures to your local hard drive

    Note: As an additional recommendation, note down the installation path under Install to, because you’ll need it in Step 2.

  5. Wait until the Java Development Kit is installed. When the process is complete, restart your computer manually if you’re not automatically prompted to do so.Installing the Java Development Kit
    Installing the Java Development Kit

Now that you’ve made sure that you have installed the correct package that installs JavaC, move down to Step 2 where we make sure that you set the path to JavaC correctly.

Step 2: Setting the Java environment variable & updating the system path

Before we start with this process, it’s important to understand that the following procedures are only applicable if you’ve made sure that the Java Development Kit is correctly installed (Step 1).

If you have installed the JDK and are still getting the “Javac is not recognized as an internal or external command“, you’ve just stumbled upon one of the most common technical issues that Java beginners face. In order to finalize the Java Development Kit on Windows, you’ll need to perform a series of manual steps. These steps should always follow the installation of JDK, even after you update the Java Development kit.

Here’s a quick guide on setting the correct Java environment variable and updating the system path:

  1. Press Windows key + R to open up a Run dialog box. Then, type “sysdm.cpl” and press Enter to open the System Properties window.Run dialog: sysdm.cpl
    Run dialog: sysdm.cpl
  2. Inside the System Properties window, go to the Advanced tab and click on Environment Variables.Go to the Advanced tab and click on Environment Variables
    Go to the Advanced tab and click on Environment Variables
  3. In the newly opened Environment Variable window, click the New button under System variable.Adding a new System variable
    Adding a new System variable
  4. In the New System Variable window, set the Variable name to JAVA_HOME and the Variable value to the path to your JDK directory. To save the changes, click OK.Configuring Variable name and Variable value
    Configuring Variable name and Variable value

    Note: If you listened to our advice at Step 1 and noted down the installation path of the JDK, you can paste it directly in the Variable value.

    Installation path of the JDK

    Installation path of the JDK
  5. Now that you’ve returned to the Environment Variables window, look for a variable named path under System variables. With the Path variable selected, click the Edit button.Select the Path variable (under System variables) and click the Edit button
    Select the Path variable (under System variables) and click the Edit button
  6. In the Edit environment variable window, click on the New button.Click on the New button
    Click on the New button
  7. Name the newly created environment variable %JAVA_HOME%bin and press Enter. Then, click Ok to apply the changes.Create a new environment variable and name it %JAVA_HOME%bin
    Create a new environment variable and name it %JAVA_HOME%bin
  8. With this last step, your Java environment should be configured. You will now be able to compile applications from CMD or check your Javac Version.JavaC was configured succesfully
    JavaC was configured successfully

Bonus step: Checking if the configuration was successful

There is one additional step that you can go through in Command Prompt in order to make sure that you’ve successfully configured the Java environment variable path. Follow the steps below to see if your configuration is working:

  1. Press Windows key + R to open up a Run dialog box. Next, type “cmd” and press Enter to open up a Command Prompt window.Run dialog: cmd
    Run dialog: cmd
  2. In the Command Prompt window, type echo %JAVA_HOME% and press Enter to see which return you get. If you see a print with the directory to the JDK, then Step 2 was successful and your JAVAC is working just fine. In the event that you see space instead of the JDK path, it means that you have failed in setting up the environment variable – in this case, revisit Step 1 and Step 2.Verifying if the Java environment variable was set correctly
    Verifying if the Java environment variable was set correctly

Photo of Kevin Arrows

Kevin Arrows

Kevin is a dynamic and self-motivated information technology professional, with a Thorough knowledge of all facets pertaining to network infrastructure design, implementation and administration. Superior record of delivering simultaneous large-scale mission critical projects on time and under budget.

В данной статье мы рассмотрим, как исправить ошибку «java не является внутренней или внешней командой, исполняемой программой или пакетным файлом.»

Данная ошибка может возникнуть при попытке запуска команды java в командной строке Windows. Первая причина ошибки – отсутствие установленной Java в системе. Вторая причина ошибки – Java установлена, но некорректно настроена. Давайте разберёмся, как это исправить.

Есть два пакета Java – JRE для запуска программ, написанных на Java и JDK – набор инструментов для разработки ПО на Java. Если вам требуется только запускаться программы, вам потребуется лишь JRE, если вы планируете разрабатывать программы – вам потребуется JDK.

Шаг 1. Установка Java

Сначала нужно определить, есть ли у вас в системе установленная Java. Проверьте следующие каталоги в системе:

%PROGRAMFILES%Java
%PROGRAMFILES(X86)%Java

Если какой-то из этих каталогов открывается и вы видите Java, значит, она установлена и её требуется настроить.

Пример установленной Java (JRE 8)

Если вы не находите подобных каталогов, вам потребуется установить Java. Как скачать, установить и настроить Java, вы можете узнать на этой странице – Установка JDK в Windows

Шаг 2. Настройте Java

Итак, вы установили Java. Теперь её нужно немного настроить, чтобы можно было запускать её из командной строки.

Выполните в командной строке команду:

control /name microsoft.system

Откроется окно «Система». Нажмите на «Дополнительные параметры системы» и в открывшемся окне нажмите кнопку «Переменные среды…»

В окне «Переменные среды» нажмите кнопку «Создать…»

Укажите следующие значения полей:

Имя переменной: JAVA_HOME
Значение переменной: <путь к установленной Java>bin

Нажмите «OK».

В окне «Переменные среды» выберите переменную «Path» и нажмите кнопку «Изменить»:

В открывшемся окне нажмите кнопку «Создать» и введите значение %JAVA_HOME%bin

Нажмите «OK».

Шаг 3. Проверка установки

Откройте командную строку (Win+R, введите cmd):

В командной строке введите следующую команду для проверки установленной Java:

java -version

Если вы видите корректный вывод программы наподобие этого, значит, вы корректно установили и настроили Java.

Если же вы снова видите ошибку «java не является внутренней или внешней командой, исполняемой программой или пакетным файлом.», значит, вы некорректно установили или настроили Java. Вернитесь на несколько шагов ранее и проверьте, что вы всё делаете правильно.

Заключение

В данной статье вы научились решать ошибку «java не является внутренней или внешней командой, исполняемой программой или пакетным файлом.» Вы научились скачивать, устанавливать и настраивать Java.

WindowsTen » Инструкции » Исправляем ошибку: «javac не является внутренней или внешней командой»

Работая с Java кодом через консоль, может появится ошибка: «javac не является внутренней или внешней командой». Как ее исправить читайте в этой статье.

Причина ошибки

Причина ошибки — заданы некорректные «переменные среды». Соответственно, необходимо указать правильные.

"Javac" не является внутренней или внешней командой, исполняемой программой или пакетным файлом

Исправление

На рабочем столе откройте «Этот компьютер»:

  1. Нажмите слева вверху «Свойства», затем слева в меню — «Дополнительные параметры системы».Система Windows
  2. В открывшейся вкладке «Дополнительно» в самом низу выберите «Переменные среды».Переменные среды
  3. Откроется содержимое. Нажмите в каждом окне поочередно «Создать».Переменные среды
  4. В окне «Новая пользовательская переменная» пропишите CLASSPATH.Новая пользовательская переменная
  5. Затем в окне «Новая системная переменная» укажите переменную PATH. В поле «Значение» пропишите директорию к пакету JDK.Новая системная переменная
  6. Перезагрузите Windows.

Кроме того, чтобы выполнить Javac, вы можете в командной строке прописать полный путь к консоли. К примеру:

"C:Program FilesJavajdk1.8.0_102binjavac.exe" MyFile.java

Рекомендую также не забывать про обновления Java. Чтобы их не пропустить, используйте программу Java Update Available.

Хороший сайт? Может подписаться?

Рассылка новостей из мира IT, полезных компьютерных трюков, интересных и познавательных статей. Всем подписчикам бесплатная компьютерная помощь.

Содержание

  1. javac не распознается как внутренняя или внешняя команда, работающая программа или командный файл [закрыто]
  2. TL; DR
  3. Переменные среды и PATH
  4. JDK против JRE
  5. Не использовать set
  6. Найти путь Java
  7. Exe установщик
  8. Почтовый файл
  9. Откройте диалог настроек
  10. чистый PATH
  11. добавить в PATH
  12. Устанавливать JAVA_HOME
  13. Закройте и снова откройте командную строку
  14. Javac не является внутренней или внешней командой…
  15. Установка Java
  16. Исправляем ошибку » javac не является внутренней или внешней командой «

javac не распознается как внутренняя или внешняя команда, работающая программа или командный файл [закрыто]

Хотите улучшить этот вопрос? Обновите вопрос, чтобы он соответствовал теме переполнения стека.

Я испытываю ошибку при попытке компилировать программы Java.

Я на Windows (это проблема, специфичная для Windows), и у меня установлена ​​последняя версия JDK.

Я попытался найти решение, связанное с PATH переменной, но ошибка не исчезла.

TL; DR

Для опытных читателей:

Вы столкнулись с одной из самых известных технических проблем, с которыми сталкиваются новички в Java: ‘xyz’ is not recognized as an internal or external command. сообщение об ошибке.

Переменные среды и PATH

(Если вы уже понимаете это, не стесняйтесь пропустить следующие три раздела.)

При запуске javac HelloWorld.java cmd должен определить, где javac.exe находится. Это достигается с PATH помощью переменной среды.

Вы можете увидеть переменные окружения следующим образом:

На моем компьютере PATH есть:

JDK против JRE

(Если вы уже поняли это, не стесняйтесь пропустить этот раздел.)

При загрузке Java вам предлагается выбор между:

Не использовать set

(Если вы все равно не планируете, не стесняйтесь пропустить этот раздел.)

Несколько других ответов рекомендуют выполнить некоторое изменение:

Не делай этого. У этой команды есть несколько серьезных проблем:

Точки № 1 и № 2 могут быть решены с помощью этой немного лучшей версии:

Но это вообще плохая идея.

Найти путь Java

Правильный путь начинается с поиска, где вы установили Java. Это зависит от того, как вы установили Java.

Exe установщик

Вы установили Java, запустив программу установки. Установщик Oracle размещает версии Java под C:Program FilesJava (или C:Program Files (x86)Java ). С помощью проводника или командной строки перейдите в этот каталог.

Каждая подпапка представляет версию Java. Если есть только один, вы нашли его. В противном случае выберите тот, который выглядит как более новая версия. Убедитесь, что имя папки начинается с jdk (в отличие от jre ). Войдите в каталог.

Затем введите bin каталог этого.

Результирующий путь Java должен быть в форме (без кавычек):

Почтовый файл

Вы загрузили ZIP-файл, содержащий JDK. Извлеките его в случайное место, где оно не будет вам мешать; C:Java это приемлемый выбор.

Затем найдите bin папку где-нибудь в нем.

Теперь вы находитесь в правильном каталоге. Скопируйте его путь. Это путь Java.

Не забудьте никогда не перемещать папку, так как это сделает недействительным путь.

Откройте диалог настроек

8RT5nyy

Попробуйте некоторые из них:

Любой из них должен привести вас к правильному диалогу настроек.

чистый PATH

добавить в PATH

Если вы используете пользовательский интерфейс, предшествующий Windows 10, убедитесь, что вы правильно разместили точки с запятой. Должен быть ровно один разделитель каждого пути в списке.

Здесь действительно больше нечего сказать. Просто добавьте путь к PATH и нажмите ОК.

Устанавливать JAVA_HOME

Не забудьте редактировать и JAVA_HOME после обновления Java.

Закройте и снова откройте командную строку

Источник

Javac не является внутренней или внешней командой…

В статье рассматривается процесс установки Java-платформы на Windows и один из способов решения проблемы, когда, несмотря на установленную в системе Java, cmd консоль продолжает выдавать ошибку типа » javac не является внутренней или внешней командой …» при попытке запустить некое подходящее java-приложение.

Всем привет, сегодня рассмотрим некоторые вопросы установки java среды в ОС Windows (я ставлю на 10-ю модель). Установка Java не относится к насущной проблеме при работе в любой операционной системе, причём при некоторых условиях даже НЕ РЕКОМЕНДУЕТСЯ. Однако в моём случае мне понадобилось реализовать небольшой проект из-под Apktool в Windows, который без Java работать просто не будет. Так что ставим.

Установка Java

Для начала проверим, не установлена ли уже какая-то версия. В консоли от имени администратора забиваем:

java ne yavlyaetsya vnutrennej ili vneshnej komandoj

Ответ меня пока устраивает — вряд ли кто-то сможет установить java в мою систему без моего ведома. Так что отправляемся на офсайт компании Oracle за подходящей версией. Однако пройдя по указанной мною же ссылке оказалось, что для моей Windows 10 32-бит (х86) современной, 10-й версии уже нет. Так что пришлось довольствоваться 8-й моделью, от обновления которой Oracle официально отказалась. Если у вас 64-х битная версия Windows — вам легче. А я качаю отсюда:

Процедура установки среды одинакова для всех:

java 32 bit x86 dlya windows 10

kak ustanovit java v windows

ustanovka java v windows

Перезагружаем Windows. Однако при попытке «пробить» возможности платформы я снова наблюдаю картину, из которой ясно, что что-то здесь не так:

javac не является внутренней или внешней командой, исполняемой программой или внешним файлом

Исправляем ошибку » javac не является внутренней или внешней командой «

papka s java v windows

peremennye sredy dlya java

put k novoj peremennoj srede

Источник

Понравилась статья? Поделить с друзьями:
  • Не работает java windows 10 64 bit
  • Не работает jakarta на windows 10
  • Не работает internet explorer в windows 10 открывается edge
  • Не работает ie8 в windows xp
  • Не работает icloud drive на windows 10