10 October, 2015

Java Programming Tutorial - Unit 1 - Hello World!

You've probably already seen this little "hello, world" thing somewhere on the Internet.  It is the most popular phrase to write to the display when learning a new programming language and has been around since the 70's.

Before we start heading into the development part of this unit, we shall install what is known as the Java Development Kit (JDK).  The JDK is an excellent set of of tools that includes compilers, runtimes, libraries - a lot of tools and buzzwords.  It's enough to know that it is necessary if you plan on programming in Java.

Installing the JDK

A explained in Unit 0, the JDK is compiled for every platform and architecture.  As a result, you'll have to select the JDK for your system.  I would assume you are running Windows, but I'll also consider Linux.  If this is already too much, just follow the steps which I label as for Windows (although I'd suggest you read up a bit on Operating Systems and general computing before proceeding).

Pre-flight checks

Before you go through a 100MB+ download, make sure you do not have a JDK installation already.  To check if you do, follow these steps:

On Window (or if you're unsure) press the Windows key (the flag icon on your keyboard) and R simultaneously.  The run dialog will open up and in it type cmd, which will open the console.  On Linux or UNIX systems, open the terminal as specified in your distribution (I expect you know this by now).

In your console (whether it is Windows or Linux), enter javac -version.  This is the command for the Java Compiler, so no there are no typos there.  If you get some meaningful output (i.e. a version number such as javac 1.8.0_4), then you can skip this installation part.  If you get an error on the lines of "not found", then you'll need to install the JDK.

Downloading the JDK

Selecting and download the JDK


The JDK setup is trivial; download it, and install it.  That's all there's to it.  So first of all, head to Oracle's website and select your version.  If you're totally unsure, just select Windows x86.  In case you're simply not sure if your system is 32 or 64 bit, do the following (if you system was made less than 4 years ago it's probably 64 bit):

Windows
Windows architecture
  • Right-click on "Computer"
  • Select "Properties"
  • Under "System", the "System type" tells you whether it is 64 or 32 bit (refer to image). 






Linux/UNIX
  • Open terminal;
  • Type uname -i
  • If it is i586, i686, or any 86, then it's 32 bit.  If it's 64 bit you'll get x64.
  

A note on Ubuntu and its derivatives

If you're working on a Ubuntu (or Mint, elementary or other derivatives) an excellent and very short guide can be found on webupd8.  I suggest following that guide for JDK on Ubuntu.

GUI Installation

Once downloaded, it is only a matter of running it and clicking next, however this setup is unfortunately bundled with unwanted software too.  So before hitting next, make sure you uncheck any field that tells you to install toolbars or whatever.  These are absolutely unnecessary and are included only for marketing.

Installed 

Now that the JDK is set up we're ready to do some work.  Despite the elaborate system, the development kit is a very simple to install.  From the installation comment, "The Java Standard Edition Development Kit includes both the runtime environment (Java Virtual Machine, Java platform classes and supporting files) and development tools (compilers, debuggers, tool libraries and other tools)" so as you see, its a great platform to work with.

Make sure everything is fine by again running javac -version.  This should print out the version number of the Java compiler.

Hello, world!

Everything is now in place and all that remains is your first class!  First what?  Java is a pure object-oriented programming language (with brand new elements of functional features since Java 8).  These are a lot of buzzwords for now, so I'll keep it simple and then elaborate on these as we go along in the series.

For now suffice it to say that everything you do in Java in contained in what is known as a class.  If you're interested, read up on object oriented programming, but for the first few units we'll keep it low.

Our first program will look like the following.  I'll explain each line afterwards.

Comments

The first thing to note is the fairly natural language in this snippet.  This is the easiest concept to grasp.  Comments in code help make your code more understandable and easy to follow.  It is of utmost importance to document your code especially when your projects get larger.  One day you'll just leave it out and when you look at your code after a month you'll regret it - so it's better to get used to it right now.

Comments can be identified by being wrapped between /* and */ (a single star, I'll explain the double ones in the code too).  Alternatively, for a single line of code, it is enough to start it with //.  Java is adamant about standard and correct coding and documentation, so much so that a particular category of comments are know as JavaDocs.  

JavaDocs are basically the multi-line documentation blocks (those between /* and */) with a very small difference and requirement.  JavaDocs have an extra * after the opening /* and are to be written in specific areas. 

After defining the other basic parts of the code, I'll go into more details on JavaDoc.  For now, it is fine to understand that we can write normal text in our code to help us understand what is happening.  Note that the compiler will ignore your comments, so complaining in code is futile :P

Class

As explained earlier, everything in Java is defined as a class.  Classes are a blueprint for an object in an object oriented system.  For now, it is not that important however it is wise too keep this in mind.  

In our case, we have just one class named HelloWorld.  You may have noted the 'public' keyword.  This will make more sense later on, so for now think of it as a requirement for your program to compile.  

In Java the file must be named as the class, so our program here must be saved to a file named HelloWorld.java.  This 'limit' actually makes thing much simpler - you don't have to remember a bunch of names for the same program.

Method

Methods are where we define functionality.  Think of this as the method in your food recipe; it tells you how to put things together to get something done.  In an object oriented system, objects (which are instances of classes, I'll explain this soon) are made up of values and methods.  Methods operate on these values to return some other value.  This concept will be explored in the next unit, however it is important to note that these values are called variables.

But let's get back to methods.  In our case we have just one method, named main, and in it we explain what to do to print our "Hello World!".  In Java a method named main is the primary starting point of the program.  Think of programs as a water hose - the main method is the point at which the water starts flowing; the origin.  This main method, though, has some extra details which we will include but will be explained later on in the series.  As you can see, we started it again with public, followed by static and finally void.  It also has a String args[] in the brackets.  Let's dissect this declaration:
  • public static are keywords for the VM which will be explained later in the series
  • void is the return type.  Remember from the definition we said that methods work on variables to return a value.  In some cases, there is no value returned by the method after it runs.  In those cases we say that the method does not return a value, so the declared return type is void.  Return values, etc are not important for now, but I'm mentioning the terms so you can get used to such concepts in context.
  • main defines the name of method.  For now it is best to use unique names, however as we'll see later on, we can use duplicate names with some limits.  You'll use the name to call the method.
  • (String args[]) is defining the method as taking one parameter or argument.  Arguments are given to your method when it is called.  In the recipe book, think of it as the book instructing you to put 100g of flour in the bowl.  The 100g is a parameter to the method "put flour".  This defines context and extra information for the method to work on.  The method can access the parameter as if it were a variable.
System.out.println 
This might seem a bit complex but let's analyse it like we did for the main.  It is good to go over this again later on after we cover more topics, so you can better 'get it'.  It is OK and expected that you will not understand the specifics right away.  However, we shall go through the line:
  • System is a class, just like our very own HelloWorld.  This class is provided with Java, so we did not have to write it.  There are various methods and variables in this class.
  • out is a variable, or member, defined in the class System.  It is not important to know the specifics, but the name is indicative enough as pointing to the output of the program.  So up till now we accesses the output of our program from the System class.  Note that a variable can also be another class.  What you need to recall now is that a variable is an instance of a class (i.e. an object, whereas the class is the type of the variable).
  • println is, finally, a method inside the out class.  This is the one which does the writing, and as you can see, we gave it a parameter, which is the text to write.
As I said, try to get the idea, but for now we'll keep it very simple and it is enough to know that System.out.println("my text"); will print "my text" to the output.

Structure Summary

So let's wrap this up after which we'll compile and run our hello world!  

Recall that in Java everything is a class.  Each class defines methods and variables (we haven't used these yet).  Variables can be other classes too.  When we create an instance of the class (which we haven't yet neither), it is known as an object.

In our basic case, we have just one class named HelloWorld with a single method named main.  Here's the pattern now: the JVM is calling HelloWorld.main().  It does this behind the scenes and as you can see it is identical to the way in which we called System.out.println().  The pattern is <class><dot><method>.  It is possible and normal to have multiple classes in one call, such as the System.out.println, which has two classes.

Going back to the JavaDoc, you can now see how the @param args is referring to the parameter passed to main.  So what we are doing in JavaDoc is explain the use of each parameter in a method.  Note also how the JavaDoc blocks are explaining the building blocks; the classes and the methods that we define.

Again, it is not vital to know these details yet, however as we go along they will start making a lot more sense.

Compiling

Compilation is fairly straightforward in Java.  Let's go back again on this process as explained in Unit 0.  Compilation in Java converts our code into byte code.  We'll use javac to accomplish this, after which we will run it using the java command which will fire up a JVM to execute the byte code.

So, in order to compile, open up your console or terminal and navigate to the directory which contains your HelloWorld.java.  For example if it is at C:\Users\james\mycode, enter cd C:\Users\james\mycode.  The same goes for Linux and UNIX systems.

Once inside the directory, enter javac HelloWorld.java

This will not do much other than compile your code silently and that's it unless you have some compilation errors.  You should note a new file now, called HelloWorld.class.  This is not a source file now but an executable for running in the JVM.  That's all there's to compilation in Java, so now onto the best part of this unit - running the program.

Running

Running your program is even simpler than compiling it.  All you need to do, in the same directory where you have the HelloWorld.class, is enter java HelloWorld in your console.  Note that we do not add the .class extension.  We are running the class, not the file per se.

If everything went well, you should see your first code running perfectly on your system, shouting Hello World! at you!  Do not underestimate this simple code.  It's where almost everyone began.  It would be ideal to experiment a bit, that's the key for your success.  Note my explanations, but doing extra reading will help you grasp concepts which you may not have correctly understood in your first reading.

Conclusion

This is your first step in a very long and never ending journey.  Do not expect that a few years will go by and you'll be done learning.  Programming is a very active field and it is best to keep looking for new concepts, languages, methodology, etc.  But this is the vital first step.  

The code for this unit may be found on the github repository.

Soon I'll be putting up Unit 2, where we shall be going into variables and more methods.  Some text in this first hands-on unit may be disorientating for the absolute beginners, but do not give up.  In a few weeks you'll be much more proficient in Java!