Building Java projects from the CLI – Part 1

Since I began programming in java one of my biggest frustrations has been my lack of understanding of what my IDE and build tools are doing under the hood. In this tutorial we will unpack a bit of the magic that goes on when it comes to organizing and compiling our java source code and libraries(jars). In particular will take a look at how the java CLI works.

I’ll be using a MAC for this tutorial but the principles and commands are almost all the same for a windows based machine.

STEP 1:

Create a directory anywhere on your machine that you would like and navigate inside of it from your terminal. I’m going to name mine “classpath-demo” and place it on my desktop.

java classpath-demo directorySTEP 2:

Once your inside the folder create a directory called classpathtutorial with the path “src/main/java/com/ryyanj/classpathtutorial”. You can do this quickly from your terminal by running

We use the src/main/java directory structure because it is a very popular convention in the java ecosystem. Build tools like Gradle even default to it. If your curious about why its used you can look here. You also might recognize the com/ryyanj/classpathtutorial as the reverse domain notation used by java as a naming convention in many projects. It is also a popular convention and is good practice to adhere to.

STEP 3:

Next create a directory called “classes” at the root of the classpath-demo directory. We will place our .class(compiled source code) files here. My directory structure looks like this in sublime text now.

STEP 4:

Inside the classpathtutorial directory create a file called ClasspathDemo.java. Paste in the following source code.

STEP 5:

Now go back to the root of the classpath-demo directory and run

This command  places the compiled files in the classes directory and compiles the ClasspathDemo.java file.

Now navigate to the classes directory and run

Now we get our result “Hello World”

Awesome! So we’ve discovered how IDEs/Build Tools pull off one of their most impressive tricks!

In the next post we’ll kick it up a notch and give our main class a dependency because we know software projects are almost always bigger than one  source file.

Add a Comment

Your email address will not be published. Required fields are marked *