Java in the Terminal

Let’s write a simple “Hello, World” program and watch the JDK in action.

In the future, we’ll be doing most of our Java coding with the IntelliJ IDE. IntelliJ contains many features to help us write Java properly and easily, including its own compiler. For now though, we’ll use a simpler text editor so we can demonstrate what we get with the JDK.

In the text editor of your choice, create and save a file called HelloWorld.java and include the code below:

1
2
3
4
5
6
7
8
   public class HelloWorld {

      public static void main(String[] args) {

         System.out.println("Hello, World");
      }

   }
Tip

If you are not able to save a file with a .java extension using a text editor, try the following:

  1. Open a terminal. Use terminal commands to find the directory you wish to save your new file in.
  2. Use the following commands to create your .java file: touch HelloWorld.java
  3. Return to your text editor and open the file you just created.
  4. Paste in the HelloWorld code from the textbook and save the document.
  5. You should now be able to run the program in the terminal by following the rest of the instructions.

We’ll discuss the syntax of this program soon, but you can likely predict that this program has an expected output of “Hello, World”. To test this hypothesis, open a terminal window and navigate to the parent directory of your new file. Run:

   java HelloWorld.java

You should see your greeting printed!

Warning

Whenever using the terminal in this course, use Git Bash as opposed to Windows Command Prompt.

Recall from the walk-through on the previous page , Java needs to be compiled before executing. Java version 17 has the capability to compile single-file Java programs without explicitly running a command to compile. If our Hello, World program were more complex and contained another file, we would need to first run javac HelloWorld.java, to compile, followed by java HelloWorld.java.