Web/_posts/2019-10-10-java_2.md
Ell 08fc481589
All checks were successful
/ web (push) Successful in 1m1s
move website content to main directory
2024-06-14 17:49:53 +02:00

9.5 KiB

layout title description tags discuss archived
blog Java Tutorial, Part 2: Intro to Conditions and Loops The second part of my post series for programming beginners. This one is all about conditions and loops.
Programming
https://twitter.com/Ellpeck/status/1182354544707198976 true

If you're reading this, then I assume you have already read the first part of this tutorial series, in which we covered setting up a program, making it print "Hello World" to the console, as well as how to declare and set the values of variables.

Today, we'll be talking about conditions and loops.1 As with the last tutorial, I'll be writing most of the code snippets first and then explaining what exactly they mean and do right after.

The if condition

Let's say you want to create a program that checks if a given number i is greater than or equal to 27. Well, you do it like this:

public class Main {
    public static void main(String[] args) {
        // This is where the code from the first tutorial would be
        // if I hadn't deleted it for visual clarity

        // Also, side note: You can use "//" to create comments:
        // lines that aren't interpreted as code.

        int i = 15;
        if (i >= 27) {
            System.out.println("i is greater than or equal to 27!");
        }
    }
}

So what we see here is called the if condition. It's structured as follows: You write the word if, followed by the condition, which is wrapped in parentheses (). You can then open curly braces {}, and any instructions that are written between them will only be executed if your supplied condition holds true.

The condition can be any statement that can either be true (correct) or false (incorrect). In this case, we're comparing two numbers with each other; there are several other ways to compare two numbers: >, <, >=, <=, != and ==, where the last two mean "not equal" and "exactly equal".2

An important thing to note at this point is that this behavior is different with String variables.3 Comparing if two strings are equal by using == will not result in the behavior you might expect. Instead, you should compare two strings using equals() as follows:

String s1 = "This is some text";
String s2 = "This is also some text";
if (s1.equals(s2)) {
    System.out.println("s1 and s2 are equal!");
}

The boolean type

A condition like this (which can either be true or false) can also be stored in a boolean variable4 whose state can then be checked using a similar if statement:

int i = 15;
boolean i27 = i >= 27;
if (i27) {
    System.out.println("i is greater than or equal to 27!");
}

The above code has the same effect as the code we looked at before. The cool thing about this method is that you can easily check if a condition doesn't hold true by simply adding an exclamation point ! in front of any boolean variable:

if (!i27) {
    System.out.println("i is NOT greater than or equal to 27!");
}

// As you can see, this is especially useful when comparing strings
String s1 = "This is some text";
String s2 = "This is also some text";
if (!s1.equals(s2)) {
    System.out.println("s1 and s2 are NOT equal!");
}

Additionally, two boolean variables (or simply two conditions) can be chained together in two ways:

int i = 15;
if (i == 12 || i == 13) {
    System.out.println("i is either 12 or 13!");
}
if (i >= 10 && i < 20) {
    System.out.println("i is somewhere between 10 and 20");
}

As you can see in lines 2 to 4, two pipes || represent the OR operator: A combined condition using it holds true if the left side is true, or the right side is true, or both sides are true.
As you can see in lines 5 to 7, two ampersands && represent the AND operator: A combined condition using it holds true if both sides are also true.

You can also wrap your checks in parentheses () to create a more complex condition, similarly to how you would use them in a mathematical expression:

int j = 10;
int k = 15;
boolean combination = (j == 12 && k == 13) || (j == 10 && k == 25);
System.out.println(combination);

The above code will cause true to be printed if j equals 12 and k equals 13 or if j equals 10 and k equals 25. Otherwise, false will be printed.

else

If you want something else to happen if a certain condition doesn't hold true, then you can do something like the following:

int i = 15;
if (i >= 27) {
    System.out.println("i is greater than or equal to 27!");
} else {
    System.out.println("i is less than 27 :(");
}

As you can see, writing else after any if statement causes the code contained in the following curly braces {} to only be executed if the if statement's condition isn't true.

Optionally, you can also combine the else with another if statement to check for a different condition. You can do this as many times as you want:

int i = 15;
if (i >= 27) {
    System.out.println("i is greater than or equal to 27!");
} else if (i <= 10) {
    System.out.println("i is less than 27, but also less than or equal to 10");
} else {
    System.out.println("i is somewhere between 11 and 26");
}

The for loop

The if condition is already pretty powerful, because you can execute different code based on different situations. Another useful thing is the for loop. How it's written and what it does can be a bit complicated to understand at first, but I'll try to break the following example down for you:

for (int index = 0; index < 3; index = index + 1) {
    System.out.println("The current index is " + index);
}

This specific for loop causes the following to be printed to the console:

The current index is 0
The current index is 1
The current index is 2

As you might be able to tell from that, a for loop causes any number of instructions in it to be executed a certain amount of times.

Its structure is pretty similar to the if statement's: First, you write the word for, followed by some loop instructions inside parentheses (), and then you open curly braces {} which contain the instructions that should be executed multiple times. The loop instructions contain three parts, which are separated by semicolons ;:

  • int index = 0; is the declaration of the loop variable: This is the instruction that will be executed before the loop starts running.
  • index < 3; is the loop's condition: Before every time the loop's content is run, a check is done to make sure that this condition is still true. If it's not true anymore, the loop stops running.
  • index = index + 1 is the instruction that is executed after every time the loop's content has finished running.

So in the case of our loop, the following things happen:

  • The index variable is declared and set to 0.
  • index < 3 is checked, which is obviously true.
  • The loop's content is run, which causes the print to the console.
  • index = index + 1 is executed, which sets index to 1.
  • index < 3 is checked, which is still true.
  • The loop's content is run again, and so on.

break

If you want to exit a for loop before its condition turns to false, you can use the break; statement as follows:

for (int index = 0; index < 10000; index = index + 1) {
    System.out.println("The current index is " + index);

    if (index >= 2) {
        break;
    }
}

This loop has the same effect as the one we looked at before. Despite the loop condition specifying that it should repeat 10000 times, it is only repeated three times, because the condition on line 4 is evaluated every time and the loop is forced to stop running once it is true.

Conclusion

In this tutorial, you (hopefully) learned what the if and for statements are and how to use them. By now, you should be able to write some more complicated code. As a little exercise, you can try to solve the following problem using the things you learned in the last two tutorials:

Given a variable i and another variable exp, calculate if the result of iexp (i to the power of exp) is less than or equal to the value of another variable j (and print the result to the console accordingly).

If you're stuck, you can check out my solution here.

Thanks for reading this tutorial and I hope it helped you out! If you have any feedback or questions about it, you can click the discussion link below and ask me on Twitter, or join my Discord server using the widget on the main page. Happy coding!


  1. I'm covering this topic before I cover what exactly classes and methods are. I think that conditions and loops take importance here, because they're used broadly in every language as well as most programs, whereas object orientation is a feature specific to some languages, as well as specific to more "complex" programs. It's also somewhat complicated, and I want to explain it right, because when I learned Java, I didn't even remotely understand it correctly at first. ↩︎

  2. Note that, when comparing two numbers, two equals signs == are used. This is different from assigning a value to a variable, which only uses one equals sign =. ↩︎

  3. Why exactly this is the case will be discussed later when we get into object orientation. The different behavior mentioned here is the case for any variable types which aren't so-called native types. Any variable whose type starts with an uppercase letter is not a native type, because it derives from a class. ↩︎

  4. Named after George Boole, a mathematician. ↩︎