1-6 Control Flow

We’re well on our way to understanding the basic building blocks of Java! Every programming language supports 3 basic structures that control the order that statements in a program are run:

    1. Sequence: statements execute in order from top to bottom in a program, unless one of the next two control structures are reached
    2. Selection: statements are only executed if the result of some condition is true, otherwise different statements can be executed instead
    3. Iteration (or “Looping”): statements are executed over and over again until some condition has been met

Relational Operators

You’ll notice that selection and iteration both rely on evaluating a condition that is either true or false. Java supports 6 relational operators to compare two values and produce a Boolean true or false result.

1-6-RelationalOps

Relational operators all have the same level of precedence and are simply evaluated from left to right as they appear.  As always, you can include parenthesis ( .. ) to control the order of evaluation and to improve readability.

Be careful not to confuse the assignment operator (=) with the equality (==) operator as this will lead to logic errors.  Reversing the operators !=, <=, and >= as in =!, =<, and =>, is a syntax error.  It’s also a syntax error if the operators ==, !=, <=, and >= contain spaces between their symbols.

The following example demonstrates all of the relational operators above to compare two integers entered by the user.

Enter first integer: 3
Enter second integer: 4
3 == 4 is false
3 != 4 is true
3 > 4 is false
3 < 4 is true 3 >= 4 is false
3 <= 4 is true
Using ?: 3 == 4 is Not Equal

Comparing Strings

It’s also important to note that these relational operators only work with numeric types, they do not work as you’d expect with reference types like strings. If you use these operators with strings what you are doing is comparing their memory addresses not the actual string values that they refer to. Try the following in the Dr Java Interactions Pane:

> String one = “Hello”
> String two = “Hello”
> one == two
false

The result is false because the variables refer to different String objects in memory.

1-6-CompareStrings1

Let’s type a few more lines:

> two = one
> one == two
true

Here we assign the memory address stored in one to two effectively making two refer to the same string object as one. After this, one and two are equal because they contain the same memory address.

1-6-ComparingStrings2

So, how do we compare two different String objects for equality? We mentioned earlier (1-2) that objects include methods to work with their data. Each String object has a method called equals() that allows it to compare the actual string value it refers to with the actual string value of a different String object. Here are a few more lines to demonstrate:

> one.equals(two)
true
> two.equals(one)
true

Notice that we can call the equals() method using either of the two String objects. The String class in the Java API includes many other useful methods, have a look if you are curious! We’ll cover strings in much more detail later.

Logical Operators

Sometimes we will need to create more complex conditions that involve more than one Boolean expression. To create compound conditions Java supports 3 logical operators: not (!), and (&&), or (||). Here is a summary of how these operators behave given Boolean operand(s).

1-6-LogicalOps

For the most part, these behave as you would expect, but the logical or (||) is a little different than the “or” we think of in English.  In English, we understand “or” to mean one or the other, but not both.  In programming, the logical “or” means one or the other, including both.

Here is an example demonstrating the result of using these operators:

LOGICAL NOT (!)
!false = true
!true = false
LOGICAL AND (&&)
false && false = false
false && true = false
true && false = false
true && true = true
LOGICAL OR (||)
false || false = false
false || true = true
true || false = true
true || true = true

Java supports short-circuit Boolean evaluation which means that logical operators only evaluate the second expression when necessary. For example, false && anything will always be false, and true || anything will always be true, it does not matter what the second expression is. Be aware that not (!) has higher precedence than and (&&) which has higher precedence than or (||) although you can use parentheses to change or clarify the order of operations.

The ?: Operator

Java supports a unique conditional operator (?:) with three parts:

First, a condition is evaluated followed by a ? symbol.  If the result of the condition is true, then the result of the overall expression will be the value right after the question mark (?).  If the condition is false, the result of the overall expression will be the value after the colon (:).  I recommend putting parentheses ( .. ) around the entire condition because the ?: operator has very low precedence.

Operator Precedence

We’ve covered a lot of different operators!  Below is a summary of Java operators and their precedence (order of evaluation) from highest to lowest.

1-6-Precedence

If you think about it, it makes a lot of sense for the assignment and compound assignment operators to have the lowest precedence (i.e., be evaluated last) since the assignment of the final result is the last operation one would want to have happen. Don’t forget that you can use parentheses to control the order of operations and also to make your code easier to follow.

You Try!

    1. Add an entry for “1-6 Control Flow” in your Learning Journal and answer the following questions:
      1. Analyse the code below, and try to predict the output. Test the code in Dr Java to see if you are right!  If you were incorrect, explain what mistake(s) you made.
      2. Update your glossary with terms you are unfamiliar with from the notes above.
    2. Write a program that asks the user for their age. If they are 18 or older tell them that they are allowed to vote, otherwise tell them that they are too young. Use the ?: operator.
    3. Extend the program above (again using the ?: operator) so that if their age is between 13 and 19 (inclusive) they are told that they are a teenager, otherwise that they are not a teenager.  Which logical operator did you use to check if a value is inside a range?
    4. Write a program that asks the user for a vehicle speed. If the speed is outside the range of 51 km/h to 60 km/h (exclusive) tell them that they need to adjust their speed, otherwise tell them that they are driving within the speed limit.  Which logical operator did you use to check if a value is outside a range?