Java tutorial for beginners, part 2


In part 1 of this series, Gary uploaded an awesome post and video explaining the basics of Java programming. Java is the official programming language of Android; so if you want to build fully-fledged Android apps from scratch, you need to familiarize yourself with how the language works.

This post will be carrying on from where that one left off and introducing a few new concepts such as arrays and conditional statements. Let’s dive in!

You may recall that in part one, you were using in order to toy around with Java without the need to set up Android Studio and the Android SDK etc.

Unfortunately, has evolved into a collaboration tool which makes getting it set up a little more complicated than before. If you aren’t already using Koding, then I recommend starting a new Java project in instead. Setting up an account takes a few minutes but it’s remarkably simple to get an environment up and running. From there, this will behave just like Koding. You’ll have your files on the left, the editor in the center and a terminal down the bottom where you can type commands.


Remember, we can use the terminal and enter javac followed by the file name (with the ‘.java’ extension) in order to compile our code then use java + file name (sans extension) to launch them. And don’t forget to save the files first after each edit!

Classes, variables and operators revisited

To recap, part one of this tutorial explained that Java was an ‘object oriented’ language. This means that we’re using classes to define ‘objects’ (objects essentially containing data/code and possessing some kind of value). Java is a classy language…

Broadly speaking then, a ‘class’ is a small section of code that performs a specific job. Object oriented programming languages don’t run linearly but rather refer to these classes as and when they’re needed. That said, every Java program starts from the same point – at the class called main(). So you need to make sure that you set off a chain of events starting from within this class or none of your code will get executed!

As well as discussing classes, part one also discussed variables. Gary described variables as being like ‘containers’ for information; information in the form of numbers, strings and more. These variables are what enable us to manipulate our data throughout our code. For a much better and more detailed explanation of all this, be sure to check out the first post.

Just like at school, operations in brackets always come first.

So if x referred to a coordinate, we might want to edit x in order to move a character across the screen. We would do this by using the statement x = x + 1 or x++. When we change our data like this, we are using ‘operators’. You can also do multiplication by using ‘*’ and handle division with ‘/’.

As in mathematics there is an order of operations (an operator precedence) for mathematical expressions. Java will always prioritize multiplication, followed by division and then plus and minus. This means that 3 * 2 + 1 is 7, not 9! Like maths, you can change this order though by using parenthesis (brackets). Just like at school, operations in brackets always come first and if you have multiple brackets, then the innermost brackets will be given priority.

By using operators you can transform the value of your variable (as in x = x + 1 or x = 50) to change its value. We also saw in part one that strings could be snipped apart, combined and otherwise manipulated. All this will come in very handy while programming but if you want to get really fancy, then you need to look at some of the other types of variables – such as arrays!

An introduction to arrays

An array is a little more complicated than the other types of variables that we’ve addressed so far. That’s because an array actually contains multiple pieces of data. Think of it like a shopping list which contains multiple ‘strings’ such as ‘apples’, ‘oranges’, ‘eggs’ etc. If we continue with the ‘container’ metaphor, then while strings and variables act like boxes, arrays act a little more like filing cabinets or bookshelves.

To create an array like this, you simply define a variable as normal but add square brackets to the end. You can then populate your array with the values you want. For example:

String ShoppingList[] = {"apples", "oranges", "pears", "milk", "eggs"};

So what’s happening here? Well first, we’re creating a string array and filling it with our shopping. Then we’re simply retrieving item three and printing it by putting the number ‘3’ in the square brackets.

Another thing you can do with an array is to retrieve its size as an integer. This then means we can use a loop to run through the entire thing:

for(int i=0; i<ShoppingList.length; i++) {

To test this, take the HelloWorld program from part 1 and replace the line System.out.println(“Hello, World”) with the definition of ShoppingList and the for loop from above. This will now display all the items on our shopping list with each one on a new line:

java example - shopping list

One thing to note is that the ‘index’ of the first item in any array is actually ‘0’ and not ‘1’. This means that the index of the last item is actually one lower than the length of the array. So if you tried to return item ‘5’ then you would get an error. There are 5 objects, but the last one is stored at ‘4’. Welcome to the confusing world of programming!

I actually tricked you a little bit here though for the sake of a useful lesson. In reality, this probably isn’t how you would go through a list. Instead you would use a ‘foreach loop’ which looks like so:

for (String element: ShoppingList) {

In the foreach loop above the variable element (which is of type String) takes the value of each item in the array, sequentially. So the first time around the loop element is equal to “apples”, on the next iteration it is “oranges”, and so on. Next time I’ll talk a little about using ‘maps’, which allow you to look up specific information in a much more dynamic manner.

Conditional statements

So we already know how to use loops to perform the same task over and over. You might remember this from last time:

 for(int i=1; i<=10; i++) {
            System.out.println("i is: " + i);

This code simply increased the value of up until the number 10. Loops form a big chunk of programming in general because we often want our code to do things that would take too long for a human to handle manually.

But counting and adding up numbers will only get us so far. For a program to be really useful it needs to be able to react to the data and make decisions on that basis. This is where ‘conditional’ statements come in.

A conditional statement basically means that you’re testing whether a statement is true before running a piece of code. We do this by asking ‘if’ something is true, then proceed to the next step if it is. You do this all the time in your real life: IF hungry, THEN eat.

The best way to explain this is simply to demonstrate it:

for(int i=1; i<=10; i++) {
    if(i == 5) {
        System.out.println("Halfway there!");
    System.out.println("i is: " + i);

This is the same loop we had earlier but now we also have a conditional statement that’s being tested each time the loop repeats itself. if(i==5) asks whether value of i is the same as 5. Note that we use ‘==’ to do this, not ‘=’. If you only use one ‘=’ sign you will get an error. A single ‘=’ means assign a value, like i=1, but a double ‘==’ means ‘is equal to?’ The statement you want to test always goes inside the brackets and the following code goes inside the curly brackets.

If our conditional statement turns out to be true, then the next bit of code runs and in this case prints ‘Halfway there!’ to the screen:

halfway there

It’s not terribly pretty though because the it says ‘halfway there’ and then ‘i is 5’. Surely ‘halfway there’ should be in the middle? Ideally, it would make more sense if we could show either one of those sentences but not both. This is where our next keyword comes in: else.

Else simply tells Java to run another section of code if the statement is not true (IF hungry, THEN eat, ELSE go to bed). To do this, we follow the closing brackets on our if statement immediately with the word else and a new set of brackets:

for(int i=1; i<=10; i++) {
    if(i == 5) {
        System.out.println("Halfway there!");
    } else {
        System.out.println("i is: " + i);

But what if you want to test more than one statement in order? In that case, else if comes in handy:

for(int i=1; i<=10; i++) {
    if(i == 5) {
        System.out.println("Halfway there!");
    } else if(i==10){
    } else {
        System.out.println("i is: " + i);

See if you can work out what’s happening here. This basically tests the first statement (i == 5) and if that isn’t true, tests the next statement (i==10). The final else will only execute then if both of the others turn out to be false.

One more trick when using conditional statements is to use ‘and’ & ‘or’. These basically allow you to run a piece of code only when two statements are both true (in the case of and) or either of the two statements are true (in the case of or). We use ‘||’ to represent or and we use ‘&&’ to represent and.

So if we had two users who could both gain access to a system for instance, we could say:

String User = "Adam";
        if (User == "Adam" || User == "Hannah") {
            System.out.println("Hello " + User);

Essentially, and and or act like ‘logic gates’ as used in electronics – but you don’t need to worry about that!

Comparing variables

Most conditional statements will check the value of variables in some way and often this will mean comparing the value of two different variables. We already saw this when we compared strings in order to check a username. You could do this with an integer if you were using a PIN.

But there are other ways to compare different variables too. For instance, the symbol ‘<‘ means ‘less than’, while the symbol ‘>’ means greater than. So you could say: if(age > 18) in order to set a minimum age for your app. This wouldn’t be quite right for most applications though seeing as ‘age >18’ is exclusive of 18! In other words, this code would only let people 19 and over in!

So instead, we might prefer to say if(age >= 18) which basically translates to ‘greater than or equal to’. Now we are letting people in who are 18 or over. We can also do the opposite with ‘<=’. If you look back to the for loop above you will notice that the ending condition was i<=10, meaning the loop would continue while i was 10 or less. Finally, ‘!=’ means ‘isn’t equal to’. In this case, the code will only run if the two variables are not the same.

It’s also possible to ‘nest’ your if statements. This way you can create some pretty complex sets of conditions to build interesting interactive apps. If you’re familiar with Excel, then you may already have some experience with nested if statements!

Next time…

Now you have conditional statements under your belt, you should find it’s possible to start thinking like a programmer. You now have all the concepts you need to build the backbone of some pretty complex programs! Learn to combine this with the Android SDK and the sky’s the limit!

But we’re a long way from done. Next time we’re going to look at how you can import classes, which basically gives us more commands to play around with and extends the capabilities of Java. I’m going to use this to get user inputs and make a basic math game. I’ll also be addressing how to use maps and some other concepts and will look in more detail at some coding best practices and the nature of Java.

If you’re itching to keep going though, refer back to part one of this series, where you can find a lot of resources and suggested further reading!

By | 2016-04-14T11:00:09+00:00 April 14th, 2016|Android Related, Just the Tablets|0 Comments

About the Author:

Vancouver, Canada