Introducing Java

Let me start with the warning: Java is not ideally suited as a “first programming language”, so hopefully you have had some experience with programming in other languages before reaching this point. There is a lot of structure and complexity associated with Java that you need to get comfortable with to complete tasks that would be quite trivial in other languages such as Python.

That said, once you get the hang of the Java-way of doing things, the benefits will flow through to whatever other technology stacks you may work with in the future. Just be prepared it will feel like qute slow-going at first.

Rather than just automatically installing an IDE to do all the work for us, it is important you understand what the IDE is doing with the core Java tools under the hood, so for the first few exercises we’re going to do a lot of the work that the IDE will do for us later, manually. Bear with me, the investment of time will be worth it.

Determining if you already have Java

To find if you have any previously existing (older?) versions of Java on your computer, look at the following locations:

You may or may not want to delete any old versions of Java. It depends on if you have other programs that use it. I can’t offer guidance on that.

Installing the Java JDK

We will use the Open JDK (Java Development Kit) rather than the proprietary Oracle JDK for this guide. Go to https://jdk.java.net/ and download the current JDK that is available and ready for use. At the time of writing it was JDK 11 and was a 174MB download.

You will download a file with a name similar to openjdk-11.0.1_osx-x64_bin.tar (Mac) or openjdk-11.0.1_windows-x64_bin.zip (Windows)

On the Mac, open a terminal:

$ cd ~/Downloads
$ tar xf openjdk-11.0.1_osx-x64_bin.tar
$ sudo mv jdk-11.jdk /Library/Java/JavaVirtualMachines/
$ java -version
$ javac -version

On Windows:

> java -version
> javac -version

Windows instructions from https://stackoverflow.com/a/52531093

Project setup

The Java-way of organising your code base is to group your functions together into “classes”. The class forms the basis of individual java files of code, each class being one .java file. You then have a collection of classes that work together to form a project. You can organise related projects together into packages. Packages can then also be organised into a name based heirachy. So to summarise:

Java uses the names of the files and folders on your disk to navigate it’s way through your collections of packages, projects and classes so it is important you take care with your names. The names must be a perfect match to those you use in your code. Java is case sensititve!

Exercise 001: Hello world

Let’s do the (in)famous “Hello world” example to walk you through what this looks like. There is an explainer for all the different elements that follows.

  1. Create a folder that is going to be the base from which all your Java projects will live. On a Mac/Linux this might be “/Users/johndoe/javaprojects”, on Windows it might be “C:\javaprojects”. Whereever. Pick a spot and remember it!

  2. Inside your javaprojects folder, create a “src” folder and a “bin” folder. All your source code (Java programming code) will live inside “src”, and all the binary files that Java creates will live inside “bin”.

  3. Packages, projects and classes are organised into a structure that looks like an inverted internet domain name. There is a reason for this. The intention is that it provides a mechanism for organising your classes so you can reuse them across multiple projects without names conflicting with each other. You can also import Java code that others have written, use it in your projects, and again the names should not conflict as they will use their internet domain name and you will use yours. The following instructions are based on the school domain name “isl.ch”. If you have access to an internet domain of your own, feel free to use your own domain name details instead.

  4. Inside the “src” folder, create a “ch” folder

  5. Inside the “ch” folder, create an “isl” folder
  6. Inside the “isl” folder, create a “basics” folder

You should now have a folder structure that looks like this:

 * javaprojects
   |-- bin
   \-- src
       \-- ch
           \-- isl
               \-- basics

This will do for our early work. Later on, when you start using Maven or an IDE, you will need to rearrange your folders a little but the above will give you a good structure that you’ll be able to drag-and-drop into the right place.

  1. Using a simple text editor (I recommend VS Code but you can even use Notepad), create a file called Exercise001.java with the following content. Make sure you get the uppercasing/lowercasing and spacing correct!
package ch.isl.basics;

public class Exercise001 {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}
  1. Open a terminal/console/command line interface (all terms for the same thing). Navigate to your javaprojects folder. For example:

On Mac/Linux:

$ cd /users/johndoe/javaprojects

On Windows:

> C:
> cd C:\javaprojects
  1. Compile your .java file

On Mac/Linux:

javac -d bin -cp bin src/ch/isl/basics/Exercise001.java

On Windows:

javac -d bin -cp bin src\ch\isl\basics\Exercise001.java

(note from here on, I’ll just show the Mac/Linux slash method. If you are a Windows user you’ll need to remmeber to use the blackslash “" when running javac)

  1. Execute your java class
java -cp bin ch.isl.basics.Exercise001
  1. If all of the above was successful, you should now be able to glory in seeing the output of Hello world! appear in your console! Congratulations, you have just successfully written, compiled and executed a Java program!

Explaining the Hello World program

Let’s look at the Hello world program line-by-line:

1 package ch.isl.basics;
2 
3 public class Exercise001 {
4     public static void main(String[] args) {
5         System.out.println("Hello world!");
6     }
7 }

For the next few exercises, your code will be almost the same as above except for the content inside the main() function (line 5) which we will change depending on what we are wanting to perform.


Command line reference

The following is a summary of useful console commands. All commands should be executed from your javaprojects folder.

Compile Java

javac -d bin src/ch/isl/basics/Exercise001.java
javac -d bin -cp bin src/ch/isl/basics/Exercise001.java

(On Windows, replace the colon : with the semi-colon ;)

javac -d bin -cp bin:project.jar src/ch/isl/basics/Exercise001.java

Place all .jar files into a lib folder and use the wildcard like so…

(On Windows, replace the colon : with the semi-colon ;)

javac -d bin -cp bin:lib/* src/ch/isl/basics/Exercise001.java

On Mac/Linux:

cd ~/javaprojects
find src -name "*.java" > sources.txt
javac -d bin @sources.txt

On Windows:

cd C:\javaprojects
dir /s /B *.java > sources.txt
javac -d bin @sources.txt

Executing Java

To execute the main function within a .class file

java -cp bin ch.isl.basics.Exercise001

JAR files

There are two types of jar files (Java ARchive files): Executable and non-executable. The non-executable type lack the presence of a main() function and are used for creating libraries of classes intended for importing into other projects. The executable type must contain (and specify) a main() function so it can be executed.

jar cvf myproject.jar -C bin .
jar cfe myproject.jar com.example.Project -C bin .
java -cp myproject.jar com.example.Project
java -jar myproject.jar

Installing ANT & Maven

ANT and Maven are build tools we will use to help automate some of the process of building your projects and managing dependancies (other people’s code you wish to use).

For Max (OS X Mavericks Version 10.9 & Higher)

# Install XCode Command Line tools
#   note - choose 'Install' rather than 'Get Xcode' unless you really want all 4GB
xcode-select --install

# Install Brew package manager if you don't already have it
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

# If you got errors installing Brew, try removing any old installs of it first
sudo rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup

# Check Brew is up to date
brew update

# Install ANT
brew install ant

# Install Maven
brew install maven

# Check the install worked
ant -version
mvn -version

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html