- How to run Java Program in cmd (Command Prompt)
- How to run a Java Program using CMD
- Create a folder
- Create a Simple Class
- Open Command Prompt / CMD
- Run the Java Program in CMD
- Additional Points
- Conclusion
- Как компилировать и запускать программу Java с помощью командной строки
- Компиляция и запуск
- Устранение ошибок
- Дополнительные статьи
- Об этой статье
- How to Run a Java Program from the Command Prompt
- Content
- Installing the Java Development Kit (JDK) in Windows
- Running a Java Program From the Command Prompt
- Setting a Permanent PATH
- Frequently Asked Questions
- How can I fix «You don’t have permission to save in this location» while saving Java files?
- How can I fix «Java is not recognized as an internal or external command» in Windows?
- Windows Command Prompt doesn’t show the results of Java command. How can I fix it?
- What is the difference between Java and Javascript?
How to run Java Program in cmd (Command Prompt)
In this article, we will learn how to run the Java Program in cmd / using command prompt.
We are using Java compiler javac for compiling the Java program and Java interpreter java for running the Java program.
Let’s get started :
How to run a Java Program using CMD
We need to follow below mentioned steps in order to run the Java in CMD :
- Create a folder in your machine.
- Create one Java class with some logic.
- Open the command prompt or cmd in your machine.
- Run the Program in CMD.
Create a folder
let’s create a folder named as Sample in your C drive of your machine.
Create a Simple Class
Let’s save this class with name – Test.java in the Sample folder.
Open Command Prompt / CMD
Open command prompt in your machine. You can also open it by typing cmd in run window.
Run the Java Program in CMD
Below are the required steps in cmd :
Now the current directory is Sample.
C:\Sample> set path=%path%;C:\Program Files\Java\jdk1.8.0_101\bin
Replace the above JDK version with your installed java version.
This will Compile the program in cmd.
This is how to run the program in cmd using interpreter.
It will print the following output :
Output:Sample Class to test
Additional Points
You need to ensure that your Windows is able to find the Java compiler and interpreter or not.
Follow below steps :
- Go to Start -> Computer -> System Properties -> Advanced System Settings -> Environment Variables -> System Variables -> PATH
- Click on the “Edit” button.
- Append the semicolon and then jdk path at the end.
- Click on OK button.
Conclusion
We have learnt how to run java program in cmd. It is a very basic question yet very important. To install java in your machine, you can visit url.
You can check your java version with following commands in cmd :
Как компилировать и запускать программу Java с помощью командной строки
Соавтор(ы): Yaffet Meshesha. Яффет Мешеша — специалист по компьютерам и основатель компании Techy, которая занимается ремонтом компьютеров, включая доставку в мастерскую и обратно к клиенту. Имеет более восьми лет опыта, специализируется на ремонте компьютеров и технической поддержке. О Techy писали TechCrunch и Time.
Количество просмотров этой статьи: 66 510.
Хотя многие среды программирования позволяют компилировать и запускать программы, их также можно скомпилировать и запустить с помощью командной строки. У Windows и Mac есть свои собственные версии командной строки, на Mac OS она называется Терминал. Процесс компиляции и запуска для Windows и для Mac практически идентичен.
Компиляция и запуск
- Чтобы сохранить файл как .java, после имени файла напишите .java и выберите Все файлы в выпадающим меню выбора расширений.
- Запомните, куда вы сохранили файл.
- Если вы не знаете, как написать программу на Java, поищите дополнительное руководство об этом. Однако, чтобы научиться компилировать и запускать программы, можно использовать любую программу, написанную на Java.
- Windows: нажмите Пуск , затем введите cmd. Чтобы открыть Командную строку, нажмите ↵ Enter .
- Mac: в Finder нажмите на вкладку Переход, выберите Программы, затем – Утилиты и кликните по Терминал.
- Если нет, вам нужно установить Java Development Kit с их веб-сайта. Его можно бесплатно скачать по ссылке: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
- Например, если вы сейчас находитесь в каталоге C:\Users\Bob\Project и хотите его изменить на C:\Users\Bob\Project\TitanProject , введите cd TitanProject и нажмите ↵ Enter .
- Если вы введете dir и нажмете ↵ Enter , то сможете увидеть список файлов, которые находятся в этом каталоге.
- Если в вашей программе есть какие-либо ошибки или возникли трудности с компиляцией, командная строка вас об этом предупредит.
- Для получения дополнительной справки ознакомьтесь с нашей статьей о том, как исправить ошибки компилятора в Java.
- После нажатия ↵ Enter ваша программа должна запуститься. Если вы получили сообщение об ошибке или ваша программа не работает, используйте метод устранения ошибок.
Устранение ошибок
- Windows: в командной строке введите java -version и нажмите ↵ Enter . Основываясь на версии Java, указанной в первой строке, введите в командной строке set path=%path%;C:\Program Files\Java\jdk1.5.0_09\bin и нажмите ↵ Enter . Замените jdk1.5.0_09 версией Java, которая у вас установлена.
- Вводите эту команду, когда будете находиться в каталоге с вашей программой Java.
- Опять же, важно, чтобы вы загрузили и установили Java JDK на свой компьютер. Ссылка для загрузки: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
Дополнительные статьи
Об этой статье
Соавтор(ы): Yaffet Meshesha. Яффет Мешеша — специалист по компьютерам и основатель компании Techy, которая занимается ремонтом компьютеров, включая доставку в мастерскую и обратно к клиенту. Имеет более восьми лет опыта, специализируется на ремонте компьютеров и технической поддержке. О Techy писали TechCrunch и Time. Количество просмотров этой статьи: 66 510.
How to Run a Java Program from the Command Prompt
Java is one of the most commonly used programming languages. It is also an IDE-intensive programming language, with tight integration with Eclipse. You can run Java programs from the Command Prompt for quick compiling and execution.
If you are just starting to learn Java, this basic guide will help you start running the Java application from the Command Prompt in Windows 10/11.
Content
Installing the Java Development Kit (JDK) in Windows
Before you can run a Java program on your computer, you’ll need to have a dedicated compiler installed. This comes within the Java Standard Edition Development Kit (JDK). It’s an essential tool for developing in Java on any platform.
The JDK is not the same as the Java Runtime Environment (JRE), which you’ll already have installed if you’ve ever used a Java application on your machine.
- Download the JDK from Oracle’s website – the Windows version. Download any of the following: an x64 installer (shown in the screen), an x64 compressed archive, or an x64 MSI installer.
Note: if you have just simple use for Java software, make sure you do not download the “Java SE Development Kit for Java SE subscribers,” which is on the same download page. If you wish to use Java’s JRE installation for Microsoft Windows, it has been moved to another page.
- Note the Windows location where Java is being installed. It will come in handy later when you’re trying to run Java from the Command Prompt.
- The installation should be over in just a few seconds. If it is taking a long time, close all of your other apps from Task Manager and reinstall the software.
Running a Java Program From the Command Prompt
public class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }
- Use the cd command to change your working directory to the directory containing your Java program. To know which directory to go to, check the saved location of Java on your PC as discussed above.
cd Documents[Java-program-folder]
- From here, locate the path to the version of the Java Development Kit (JDK) on your computer. For example, if you’re running 64-bit Windows, that will often be in “C:\Program Files\Java.”
set path=%path%;C:\Program Files\Java\jdk-"Java Version Number".bin
- You may need to change the directory path to reflect the current version of Java. Make sure you’re using the Java Development Kit (JDK) directory and pointing to the “bin” folder.
Note: the Java Runtime Environment (JRE) folder also contains a “bin” folder but doesn’t hold the Java compiler. If you get errors around the compilation, make sure you’re using the correct directory path.
- Compile the Java program with the javac command as shown below. Be warned that you won’t see anything happen. However, if you use the dir command, you’ll notice a new file in your directory ending in the “.class” extension, indicating the program has been compiled.
You’ll see the program run within the Command Prompt window, but there’s one more task you can do to make sure your Java program runs smoothly: set your path.
Setting a Permanent PATH
The above command doesn’t set your Java compiler PATH permanently. It sets the environment variable for that session, but that change will be wiped away when you close the Command Prompt session.
Setting your Java compiler PATH permanently can come in handy if you want your compiled Java programs to run smoothly after a PC reboot. This helps launch the requested programs quickly from the Command Prompt window (or a third-party software like Eclipse).
Follow the steps below to change your PATH variable for all future sessions.
- Click the “Environment Variables” button at the bottom after you’ve switched to the “Advanced” tab in the “System Properties” window.
- Paste the directory path you used above into the text box. Again, make sure you’re using the Java Development Kit (JDK) directory and not the Java Runtime Environment (JRE) directory next to it.
This article featured a simple Java program, but you can initiate almost any Java program from the Command Prompt. The procedure is straightforward regardless of the nature of your program.
Frequently Asked Questions
How can I fix «You don’t have permission to save in this location» while saving Java files?
Some users may get a “You don’t have permission to save in this location” error while saving Java files in Windows. Even though you are the administrator of your PC, this error shows up out of nowhere. To fix the problem, right-click the Java folder’s “Properties” and navigate to the “Security -> Advanced -> Select User or Group.”
In the “Advanced Security” settings for Java, change the “Owner” from “System” to whatever user account you have used to log in to the device. You can determine the correct name from “Check names.” Just enter the text, such as “Desktop,” “Administrator,” or “Users,” to enable full permissions to the folder. Click “OK” and save the changes.
How can I fix «Java is not recognized as an internal or external command» in Windows?
The best way to fix “Java is not recognized as an internal or external command” is to add Java’s bin directory to your computer’s path, as covered above.
Windows Command Prompt doesn’t show the results of Java command. How can I fix it?
If your Windows Command Prompt doesn’t show the results of a Java command you’ve entered, there are two solutions: run the Command Prompt in Administrator Mode or find your “Java.exe” file in the folder location and open its “Properties.” Then, navigate to the “Compatibility” tab where you will have to uncheck the “Run this program as an administrator” option.
What is the difference between Java and Javascript?
Don’t confuse Java with Javascript, as they are two different entities:
- Java came before Javascript. It was founded by Sun Microsystems in 1991-1995. Javascript was founded later by Netscape, an old browser company. Basically, Javascript is a very lightweight version of Java and still commonly used in browsers.
- Java is a compiled program, whereas Javascript is interpreted.
- Java is a static typed program, whereas Javascript is dynamically typed.
- Java uses classes, and Javascript uses prototypes.
Image credit: WrightStudio via AdobeStock. All screenshots by Sayak Boral.
Sayak Boral is a technology writer with over eleven years of experience working in different industries including semiconductors, IoT, enterprise IT, telecommunications OSS/BSS, and network security. He has been writing for MakeTechEasier on a wide range of technical topics including Windows, Android, Internet, Hardware Guides, Browsers, Software Tools, and Product Reviews.
Our latest tutorials delivered straight to your inbox