How to compile and run Java programs from the Terminal on macOS?

As an aside, some people prefer to create code directly in the Terminal (rather than use an SDK). Here is how to compile and run Java from the Terminal in OS X.

  • Open Terminal.
  • Enter mkdir HelloWorld to create a new directory and cd HelloWorld to move into it.
  • Enter touch HelloWorld.java to create an empty Java file.
  • Now enter open HelloWorld.java to open and edit the file in default text editor.
  • Or if you wish you can edit HelloWorld.java with your favourite editor ( type "open -e Helloworld.java" to open it in TextEdit).
      • -e                  Opens with TextEdit.
      • -t                   Opens with default text editor.
      • ~/                  Opens with default text editor.
  • In the default editor type out the following code:
  • public class HelloWorld {

        public static void main(String[] args) {

            System.out.println("Hello World!");

        }

    }

  • Press Command+S to save the file and then close the editor.
  • Now compile the program by entering javac HelloWorld.java in Terminal.
  • Enter java HelloWorld to run it.
  • You should see Hello World outputted into the Terminal.

Comments

Popular posts from this blog

n - Interactively Manage Your Node.js Versions on macOS