A little bit of Java

Introduction

Life is all about learning and maintaining the skills you have. I started off writing software in procedural languages, then moved on to C++, being object orientated, then Java came along and I fell in love with it. I found it much easier not having to worry about memory management and having so much ‘out of box’ components, especially graphical ones. So let us learn and revisit the language and discover it.

Disclaimers

Ubuntu® is a registered trademark of Canonical Ltd – ubuntu.com/legal/intellectual-property-policy.

Other names / logos can be trademarks of their respective owners. Please review their website for details.

I am independent from the organisations mentioned and am in no way writing for or endorsed by them.

The information presented in this article is written according to my own understanding, there could be technical inaccuracies, so please do undertake your own research.

Equipment and prerequisites

Instead of a virtual machine, this time I’ll be using a Raspberry Pi (www.raspberrypi.com/for-home) because they are popular and have so much good documentation on how to use them. And just like a virtual machine, if you mess up, then you just have to wipe the storage that you use and start again without consequences to your own system. I believe that you can use any other Linux based single board computer or even a virtual machine with this post if you wished. The Pi uses a variant of Debian Bullseye (www.debian.org/releases/bullseye), called the ‘Raspberry Pi OS’ (www.raspberrypi.com/software), therefore I suspect that all the instructions will be applicable to other distributions based on Debian, such as Ubuntu. I don’t have the graphical user interface, GUI, running, but if you do then just use a terminal.

We will start from the point where you have a running Pi or Virtual Machine, with or without the GUI, and that you can use the terminal (en.wikipedia.org/wiki/GNOME_Terminal). This can be either directly with the Pi connected to a monitor, or remotely with ‘ssh’ as I’m using.

Java background

Java was designed by James Gosling and others at Sun Microsystems (en.wikipedia.org/wiki/Java_(programming_language)), which between 2006 and 2007 was (for the most part) made Free and Open Source (en.wikipedia.org/wiki/Free_and_open-source_software)). Since then Oracle (en.wikipedia.org/wiki/Oracle_Corporation) acquired Sun Microsystems and distribute their own versions both commercial and non-commercial. As I’m a software engineer and not a lawyer, then I thought it best you use the ‘OpenJDK’ (en.wikipedia.org/wiki/OpenJDK) version, and for simplicity, the latest made available for the Pi via its standard ‘apt’ repositories (en.wikipedia.org/wiki/APT_(software)). This is the ‘Java Development Kit’ containing all the software we need to make our running programs.

Installing Java

First ensure that your repositories are up to date with ‘sudo apt update’, then see what versions are available with ‘apt-cache search openjdk’. My list at the time of typing shows ‘17’, even though the current general availability release version is ‘19’ (jdk.java.net/19) and seventeen is showing as superseded (jdk.java.net/17) with ‘warnings’, hence that’s why I’m using the Pi and in the context of a ‘non-production’ environment.

We need to use the JDK and not the runtime environment package, JRE, and as I’m running without the GUI, then I’ll select the ‘headless’ version. If you’re in doubt or are using a GUI, then select the version without the ‘-headless’ postfix. Thus, type ‘sudo apt install openjdk-17-jdk-headless’ and let the install proceed.

To confirm that everything has worked, type ‘java –version’ and ‘javac –version’ being the runtime and compiler respectively.

Two small programs

The first of our programs will output ‘Hello’ and the second will echo what we tell it. Both are small and will allow us to understand the basics.

Java is an ‘object orientated’ language that uses a similar syntax to PHP, C, C++ etc. It has functions as well as methods, variables, employs the concept of ‘scope’, all of which I’ve covered before, so if you’re not familiar with this, then please see my series of posts entitled ‘The first step’:

Indeed do also look at my other posts under the tag of ‘code’ (www.elearningworld.org/tag/code). Then this will help you understand my explanations of the programs here.

Firstly if we look at ‘Hello.java’:

/*
 * Hello
 *
 * @copyright  2022 G J Barnard
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

public class Hello {
    public static void main(String args[]) {
        System.out.println("Hello");
    }
}

Then compile it with ‘javac Hello.java’, which will produce a ‘.class’ file that we can run with ‘java Hello’, to get the output:

Hello.java compiling and running

We see that the word ‘Hello’ is being output. The file starts with a comment section between ‘/*’ and ‘*/’ that is ignored and just there for us. Then we have the program itself:

public class Hello { Everything in Java is a ‘class’ for which the filename must be the same. Unlike PHP, you can only have one class per file.
public static void main(String args[]) { This is our ‘main’ method that is called first when we run the program. The ‘args’ array is our list of arguments that were passed to the program from the command line. We don’t use it here, but we still need it to avoid the error ‘Error: Main method not found in class Hello, please define the main method as: public static void main(String[] args)’ when we attempt to run the program.
System.out.println("Hello"); This calls the method ‘println’ within an instance of the ‘PrintSteam’ class (docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/PrintStream.html#println(java.lang.String)) being ‘out’ which is an attribute (field) of the ‘System’ class (docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/System.html#out) to output the word ‘Hello’.

Our second program is called ‘Echo.java’:

/*
 * Echo
 *
 * @copyright  2022 G J Barnard
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

 public class Echo {
    public static void main(String args[]) {
        Echo us = new Echo();

        if (args.length < 1) {
            us.output("- Add text when running, i.e. java Echo Me or java Echo \"I'm me\"");
        } else {
            us.output(args[0]);
        }
        System.out.println("Args length: " + args.length);
    }

    private void output(String s) {
        System.out.println("Hello " + s);
    }
}

Which will give different output depending if we supply an argument. Again compile and run with ‘javac Echo.java’ and ‘java Echo’ respectively:

Echo.java compiling and running

Now to describe what is going on, ignoring what we have already learnt:

Echo us = new Echo(); This creates a new instance of the Echo class and puts it in the ‘us’ attribute.
if (args.length < 1) {
us.output("- Add text when running, i.e. java Echo Me or java Echo \"I'm me\"");
} else {
us.output(args[0]);
}
If there are no arguments, i.e. the array has less than 1 elements, then call out ‘output’ method with an informational string, else call it with the first argument.
System.out.println("Args length: " + args.length); Output the number of arguments.
private void output(String s) {
System.out.println("Hello " + s);
}
Our ‘output’ method that takes a ‘String’ (docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html) as a parameter and output it with a bit of preceding text.

I hope this all makes sense.

Conclusion

Do have a go and if you’ve not got a Pi, similar or old machine, then perhaps create a virtual machine instead.

What do you think? Please let me know in the comments.

Gareth Barnard
Latest posts by Gareth Barnard (see all)
blank

Gareth Barnard

Gareth is a developer of numerous Moodle Themes including Essential (the most popular Moodle Theme ever), Foundation, and other plugins such as course formats, including Collapsed Topics.

One thought on “A little bit of Java

  • 17th November 2022 at 2:30 pm
    Permalink

    I never learned Java, so will be picking up some background knowledge through these posts 🙂

    Reply

Add a reply or comment...

%d bloggers like this: