Part 3: Control Statements

Sep 7, 2016
Part 3: Control Statements
  • Crash Course to Java

    Part 3: Control Statements



    The statements in your source files are generally executed from top to bottom. However, control statements may be used to break up the flow of execution with decision making, looping, or branching. This allows for far more complex functionality.

    Section A: Conditional Execution
    If statement: An if statement is simply, if an expression evaluates to true, execute some code. Example of an if-statement:
    Code (Java):
    if (A < B) {
      System.out.println("A is, in fact, less than B! Hooray!!");
    }
    If... else statement: After an if statement, you can then use an optional else statement, which executes the statement or block if the statement evaluated to false. Example:
    Code (Java):
    if (A < B) {
      System.out.println("A is, in fact, less than B! Hooray!!");
    } else {
      System.out.println("A is not less than B. Booo :(");
    }
    You can take advantage of the nature of else to make "else if" blocks.
    Code (Java):
    if (A < B) {
      System.out.println("A is, in fact, less than B! Hooray!!");
    } else if (A == B) {
      System.out.println("A is equal to B.");
    } else {
      System.out.println("A is not less than B. Booo :(");
    }
    Fun Fact: Contrary to what many would probably tell you, and unlike a lot of other languages, else if is not actually its own keyword in Java. If and else statements simply execute the statement that follows them. When you use brackets, you are turning everything inside that block into the statement for the if to execute. So if you put an 'if' after else, you are actually just making the if statement the execution statement for the else.


    Nested if statements: You can use one if (or even an else if) inside another if or else if statement! Example:
    Code (Java):
    if (A < B) {
          System.out.println("A is, in fact, less than B! Hooray!!");
        if (A == 10) {
          System.out.println("A is also equal to 10!!");
        }
    } else {
      System.out.println("A is not less than B. Booo :(");
    }
    Switch statement: A switch statement compares a variable to a list of possible values. When checking if a variable is a lot of different possible values, using a switch statement in place of a chain of if else statements can make your code easier to read/follow and may even make your code run a little faster! As with if... else statements, there you can also have a catch-all with switch statements by using the "default" case.
    Code (Java):
    private void praise(char testGrade) {
      switch (testGrade) {
        case 'A':
          System.out.println("Amazing!");
          break;
        case 'B':
          System.out.println("Good job!");
          break;
        case 'C':
          System.out.println("Great try");
          break;
        case 'D':
          System.out.println("You passed");
          break;
        case 'F':
          System.out.println("Better luck next time");
          break;
        default:
          System.out.println("Invalid grade");
          break;
      }
    }
    The conditional operator: Earlier, we talked about the conditional operator. This can be used in place of if-statements in some cases.

    Section B: Loops, Loops, Loops, Loops, Loops...
    Ha! Get iiiit? Geeet iiiit?... Anyway, loops can be used when you have a block of code that you want to be executed multiple times. There are a few different types of loops.

    While loop: A while loop repeats a block of code while a given statement is true. Before each execution, the statement is re-evaluated, and it will continue until the statement is no longer true.

    You may have seen something like this before:
    Code (Java):
    while (true) {
    ...
    }
    Since the statement is simply "true", this means it will just execute until the task is ended.

    For loop: A for loop is a compact method for iterating over a range of values. The form of a standard for loop is this:
    Code (Java):
    for (initialization of variable; continuation case; increment) {
    ...
    }
    Initialization of variable is initializing the variable intended to be looped upon. For example, int i = 0;. The continuation case is an expression which must evaluate to true for the loop to continue. Example: i < 10. Increment is where you increment the value towards the termination. Example: i++. Put these together, and you get a block of code which will run exactly 10 times:
    Code (Java):
    for (int i = 0; i < 10; i++) {
    // Will run 10 times
    }
    Do... while loop: A do... while loop is like a while loop with one major difference: the condition for continuing the loop is tested at the end of the loop rather than at the beginning.

    Enchanced for loop: In Java 5, the enhanced for loop was introduced. This is most useful for iterating over a collection of elements such as arrays, lists, and sets. The syntax is simple:
    Code (Java):
    for (initialization of variable : iterable) {
    ...
    }
    Like in the standard for loop, initialization of variable is simply a variable that can be used inside the for loop. The iterable is any iterable (haha). For example:
    Code (Java):
    List<String> list = Arrays.asList("one", "two");
    for (String var : list) {
      System.out.println(var);
    }
    ... would print one, and then print two.
    Section C: Flow Control
    Flow control statements allow you to specifically control the flow of execution of certain code. In places where code could potentially cause issues if run under certain conditions, these statements are particularly helpful and sometimes necessary.
    Return statement: The return statement can serve a couple of different purposes.
    In a void method, a method which does not return any value, a return statement can be used simply to exit the method like so:
    Code (Java):
    private void drawToScreen() {
      if (!isRunning()) {
        return;
      }
    }
    This can sometimes be used in place of nested if-statements to make code more readable.
    Any value that is not declared void must contain a return statement with a value to return, like this:
    Code (Java):
    private boolean isRunning() {
      return game == null ? false : true;
    }
    Continue statement: A continue statement can be used within the body of a loop to skip execution of the following code and move on to the next iteration of the loop. For example:
    Code (Java):
    for (int i = 0; i < 10; i++) {
      if (i == 5)
        continue;
      System.out.println("Count: " + i);
    }
    This would print numbers 0-9, but would exclude 5 because of the continue statement.

    Break statement: A break statement immediately terminates a loop and resumes with the next statement following the loop. Example:
    Code (Java):
    for (int i = 0; i < 10; i++) {
      if (i == 5)
        break;
      System.out.println("Count:" + i);
    }
    This would print numbers 0-4, and then it would terminate the loop due to the break statement.

    Break statements are also used to terminate a switch statement, as you saw in Section A.

    Continue the guide in Part 4!
  • Loading...
  • Loading...