A Java application can be run and compiled from the command line.
Although running Java apps from the CLI during normal development is not entirely common, it is essential to know how it is done.
Steps to Create and Compile Java from CLI
Please follow the steps below to run your first Java app from the CLI.
1. Change Into Your Working Directory
First, open your terminal and ensure you're in the right working directory. For instance:
cd ~/Documents/<working_directory>
2. Create and Write a New Java File
Use Vim to create and write a new Java file.
vim HelloWorld.java
Tip: If you're unfamiliar with Vim, refer to this page for a quick introduction/refresher.
3. Paste the Main Method
Paste the following content into the file (after hitting i to enter "insert mode" in Vim).
public class HelloWorld {
public static void main(String[] args){
System.out.println("Hello World!!!");
}
}
4. Save and Quit the File
Exit "insert mode" by hitting the escape key, then save and quit the file.
[esc]
:wq
5. Compile the File
You now need to compile the file - you will use the Java compile (javac) to do this:
javac HelloWorld.java
6. View Newly Created Class File
List the directory contents, and you'll see that you now have a class file named HelloWorld.class. This class file contains the byte code created by the Java compiler that the JVM will translate into machine code.
7. Run the App
To run the Java app, you use the java command.
java HelloWorld
Note: you do not need to add the .class extension because the java command only works on files with the .class extension.
8. View Result
You should see Hello World! printed out in the CLI window.
Summary: How to Run Java from the Command Line
A Java application can be entirely written and run from the CLI. In this article, you learned how to write a basic app that prints to the command line.
Steps to Create and Compile Java App from CLI
cdinto your working directory- Create and write a new Java file
- Paste the
main()method - Save and quit the file
- Compile the file
- View newly created class files
- Run the app
- View result
You've already created and run your first Java application. Congratulations!!