Best daily deals

Affiliate links on Android Authority may earn us a commission. Learn more.

Java tutorial for beginners, part 2

In part 2 of our basics of programming in Java series we'll explore conditional statements, arrays and more!
By
April 14, 2016

20160414_121809

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!

A method to the madness

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 – describing an object. 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 with a method 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!

So what is a method? Gary explained methods earlier in the context of classes, but let’s take a moment to recap on their behavior and how they can be used within a straight-forward program. A method is basically a small segment of code that lives inside curly brackets. It will then complete a set job that you can call upon at any point in your code. So for instance, if you had a method that looked like this:

Code
public void sayHello() {
        System.out.println("Hello!");
    }

Then you could write sayHello() anywhere in your code and it would automatically print out ‘Hello’ to the screen. Using methods in this way allows us to avoid repeated the same lines of code and thereby keep things much more neatly organized.

Methods are ‘void’ unless they return some kind of data to the rest of the code.  A non-void method on the other-hand might look like something like this:

Code
public String sayHello() {
        return "Hello!";
    }

This is ‘returning’ a string and so it is a ‘public string’. That means that we can use the method as though it were a string, so:

Code
System.out.println(theText);

Normally, we would include some more code in the method that would manipulate the string in some way. For instance, we could return the day or the time. You can return mostly any type of data. You could just as easily use public int sayTheTime() for examplle.

Finally, we can use the brackets in order to ‘feed in’ variables that can be used within the code inside method. So for instance, we could send a number in, perform a sum on that number and then return the result:

Code
public int timesTen(int numberToChange) {
        return numberToChange * 10;
    }

Remember that you can also access methods from other classes, as long as the methods are ‘public’ rather than ‘private’. And the method is ‘static’, then that means that you don’t need to create a new instance of the object in order to access it. This is mainly a matter of organization, so don’t worry right now if you don’t understand everythin. But you’ll see methods used constantly and it’s useful to know their role.

An introduction to arrays

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.

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:

Code
String ShoppingList[] = {"apples", "oranges", "pears", "milk", "eggs"};
System.out.println(ShoppingList[3]);

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:

Code
for(int i=0; i<ShoppingList.length; i++) {
    System.out.println(ShoppingList[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:

Code
for (String element: ShoppingList) {
    System.out.println(element);
}

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:

Code
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:

Code
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:

Code
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:

Code
for(int i=1; i<=10; i++) {
    if(i == 5) {
        System.out.println("Halfway there!");
    } else if(i==10){
        System.out.println("Finished");
    } 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:

Code
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,. My advice is to start slow however and follow along with some tutorials to begin with. Once you learn to combine this with the Android SDK, 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 program that you can actually try out.  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!