Skip to content
Ryan James
Menu

← Java10 min read

Control Statements

Program flow and program control is essential to writing an algorithm in any program language. The concept of looping through iteration and combining this with decision making statements is the building blocks to any powerful program.

Control Statements

Program flow and program control is essential to writing an algorithm in any program language. The concept of looping through iteration and combining this with decision making statements is the building blocks to any powerful program. The concepts transfer over to any programming language whether that be Python, JavaScript, or Java. The only thing that changes is the syntax or the way that these concepts are implemented in the programming language of choice. If you’re reading this section, that means you’re interested in learning this for Java.

Let’s start with selection statements. Selection statements are the decision making statements in programming and follow the basic principle of: if some condition is true, then execute a block of code. These can be combined with else statements to make more complex decision making statements. Let’s look at some examples.

public class SelectionIntro
{
    public static void main(String[] args){
        boolean isHot = true;
        if(isHot){
          System.out.println("It is hot outside.");
        }
        System.out.println("End of weather announcement.");
    }
}

When the code segment above runs, the output will be: It is hot outside. and on a new line: End of weather announcement. Both of these lines will print because the condition inside the if statement is true, the first print statement executes. The second print statement will execute always. Take a look at a similar example:

public class SelectionIntro
{
    public static void main(String[] args){
        boolean isHot = false;
        if(isHot){
          System.out.println("It is hot outside.");
        }
        System.out.println("End of weather announcement.");
    }
}

When this runs, only one line will print and that’s the last line. The output will be: End of weather announcement. The first print statement never executes because the conditional statement is false.

This example would make a whole lot more sense if it was an either or situation. If it’s hot, then print a message saying that, but if not, then say that. This makes more sense to use an if with an else to go along with it.

public class SelectionIntro
{
    public static void main(String[] args){
        boolean isHot = true;
        if(isHot){
          System.out.println("It is hot outside.");
        }
        else{
          System.out.println("It's not really hot outside.");
        }
        System.out.println("End of weather announcement.");
    }
}

Looking at the code segment this time with its subtle changes, now 2 print statements will execute. The output will be: It’s not really hot outside. and on a new line: End of weather announcement. This happens because since the if is false, then it will trigger the else to execute. The if-else statement is really useful when a program needs to branch based off of an either or decision, similar to flipping a coin to decide who gets the ball first in a team game.

This idea can be extended even further. What if it was possible to put a camera on a radar to hand out speeding tickets to a driver? So let’s think about this for a minute. The speed limit will be 45 mph, and once the camera picks up a car going over that, then a ticket should be assigned. But there should be different kinds of tickets, one for just over the speed limit and then a second level for if someone is going 70 mph or higher. Let’s see how that would be implemented.

public class SelectionIntro
{
    public static void main(String[] args){
        int speed = 55;

        if(speed <= 45){
          System.out.println("No speeding ticket. Thanks for being a safe driver.");
        }
        else if(speed > 45 && speed < 70){
          System.out.println("Speeding ticket for you. You need to slow down.");
        }
        else{
          System.out.println("Ticket for reckless driving. You need to get out of the car.");
        }        
    }
}

In the example shown above, the variable for speed has been set to 55. Then it will go through the decision making structure that has been made. Looking at the way it has been set up, it is only possible for one print statement to execute. Based on the size of our number, the middle statement will execute since it falls in the range of greater than 45 and less than 70.

More complex selection statements can be created by extending this example with more else if statements or by using nested if statements by placing an if statement inside of an if, else if, or else statement. The control and flow of a program can also be altered by using iteration with loops. That’s the next thing that is going to be looked at below.

Using loops, a block of code can be repeated however many times that it needs to be run for the algorithm to run properly. There are a few different types of loops that can be used in Java like a for, while, do while, or the enhanced for loop that is useful for iterating over data structures. For writing algorithms using primitive data types, the most frequently used loops are the for and the while loops. In both of these loops, there will be variables that need to be created that will keep track of when the loop starts and what conditions will cause the loop to terminate. Any algorithm that requires iteration can be written using a for loop or a while loop. The difference will be in the efficiency of the implementation of the algorithm.

public class IterationIntro
{
    public static void main(String[] args){
        for(int i = 1; i <= 10; i++){
          System.out.print(i + " ");
        }   
        System.out.println();
    }
}

In the example that is shown above, the for loop will print the integers from 1 to 10 all on one line separated by one space. When the loop is done, the empty print statement will move to a new line. When writing this kind of loop, all of the information goes inside the parentheses of the loop declaration: the variable i gets declared, then the conditional statement that terminates the loop, then lastly the iterator comes last. All of these are user defined and can be changed depending on how the algorithm needs to function. The loop doesn’t have to increment, it can even decrement and count down from 10 to 0. Let’s look at how we can achieve the same output but using a while loop.

public class IterationIntro
{
    public static void main(String[] args){
      int i = 1;
        while(i <= 10){
          System.out.print(i + " ");
          i++;
        }   
        System.out.println();
    }
}

While the output of these 2 loops doesn’t differ, the way the code is set up does. In the while loop, the variables that dictate how the loop operates must be declared outside of the loop and because of this, they will remain throughout the program. In the for loop, the variable i was created as part of the loop and gets destroyed once the loop terminates. So it’s really down to data management and the look and appearance of the loop. Both of these loops will accomplish the same task but will be written differently. Let’s look at a couple more examples to see when one loop would be more efficient.

public class IterationIntro
{
    public static void main(String[] args){
      int n1 = 1;
      int n2 = 1;
      System.out.print(n1 + " " + n2 + " ");
      for(int i = 0; i < 8; i++){
        int sum = n1 + n2;
        n1 = n2;
        n2 = sum;
        System.out.print(n2 + " ");
      }
    }
}

In the example shown above, the first 10 numbers in the Fibonacci sequence are printed: 1 1 2 3 5 8 13 21 34 55. The first two numbers are printed on their own and then there is a loop that runs 8 times to print the rest of the Fibonacci numbers. The reason a for loop is used is because there is a specified point when the loop needs to stop, after it has printed the 10th number in the sequence.

public class IterationIntro
{
    public static void main(String[] args){
      int number = 9173;
      int reversed = 0;
       while(number > 0){
        reversed = reversed * 10 + number % 10;
        number = number / 10;
      }   
      System.out.println(number + " " + reversed);
    }
}

In the example shown above, the number 9173 is taken into the loop and then using each digit one at a time, the number is reversed into 3719. This is a good use of a while loop because as the variable number changes, the length of the loop will change too. This is why it makes more sense to solve this problem with using a while loop.

Now that you have some background on primitive data types, writing selection statements, and writing iteration statements, you have a solid base for how to start writing programs in Java. There is a lot more to take in like Strings, creating objects, and using data structures…but all in due time. I hope the examples provided help you get started on your Java programming.

Keep coding!
Ryan