Compiling Java programs from Terminal in Catalina 10.15.4
“Gee, wouldn’t it be great if I could tinker around with Java on my Mac without having to download a bunch of new Apps that I don’t understand and have to learn?”
Hey! Guess what? You can!😀
All you really need is the Java Developer Kit and Terminal.
* Note: I’m running Catalina 10.15.4 at the time I wrote this post.
Download and install Java Developer Kit from Oracle. https://www.oracle.com/java/technologies/javase-downloads.html
Make things easy on yourself and download the installer .dmg and not the compressed file.
That’s it! Just Find and launch Terminal (Application > Utilities > Terminal) and now you’re ready to code.
Start with making a new directory (Normal folks call it a folder) I’m gonna call my directory “Java”
Type mkdir Java then press “return” or “enter”
Note: mkdir stands for “make directory”
If we look in my Home folder, we see a new folder appears called “Java”
Now I need to tell Terminal to go into the Java directory.
Type “cd Java”
Note: cd stands for “change directory”
Now I’m going to create a new empty file. I can name it anything but I’m gonna call mine “HelloWorld.java”
Type: touch HelloWorld.java
Note: “touch” basically tells the computer to make a new file. “HelloWorld.java” is the name.
If we look in Finder again, we can see a new file appears in the Java folder called “HelloWorld.java”
Now I could just open this empty file in Text Editor but this time I’m going to use the text editor in Terminal called “nano”.
Type: nano HelloWorld.java
Note: “nano” launches the program call “nano” and typing “HelloWorld.java” tells nano to open that file.
Now my window changed. That’s okay. It’s supposed to do that. This is what the nano interface looks like. You can see the top bar shows it’s reading my HelloWorld.java file. There’s nothing below that because I having written any code yet. It is still a blank document.
Time to time some code. I’m going to do the obligatory “HelloWorld” program.
Note: I like to hit enter to leave space between the lines. It seems to run better. I don’t know why.🤷♂️
Type the following or copy and paste:
public class HelloWorld{ public static void main(String[] args) { System.out.println("Hello World!"); } }
I use the control key + the X key to close the document.
The bottom of the window changes. Nano just wants to know of I want to save the changes I’ve made to the document.
I press the “y” key for yes. The bottom of the window changes again. This is just giving me one more chance to change the name of the file. I leave everything as is and press return.
To run my program, I just need to call on Java followed by the name of the Java file I want to run.
Type: java HelloWorld.java
Hello World! Get printed out on Terminal.
Is there a Integrated Development Environment I could use to code Java?
For sure. I could use Netbeans or even Xcode but that’s for another blog post.