Lecture 4: Conditional Statements

Shift in course format

We are going to start picking up the pace in both lectures and labs at this point in the semester. Some items to be aware of:

  • We will be spending class time going over coding exercises
  • You will have homework exercises you are expected to complete and submit; we will start these in class
  • Labs will be used to 1) proctor quizzes and 2) work on the coding exercises mentioned
  • Therefore, you should plan to spend 5-10 hours a week outside of lectures and labs working on coding exercises

Objectives

  • Write and evaluate boolean expressions.
  • Mentally execute code with if, if-else, and if-multi-else statements.

Boolean variables

In order to make a decision, we need a way to represent a situation that is true, versus one that is false. For example, imagine you need to decide whether or not to do some extra credit for a course. You might ask yourself, “will these extra credit points change my final grade in the course?” If yes, you would do the extra credit; if no, you would skip it.

We could rephrase this question as a statement: True or false: doing extra credit will change my final grade in this class. If this is true, then you would do the extra credit, etc.

In Java, a boolean variable (or expression) has either the value true or the value false – both of these are reserved words in the language. For example, you can do the following:

int num = 0;
num = 3;

boolean thing = true;
thing = false;

Why are conditionals useful in computation?

With the compiler recognizing boolean types and expressions, it is now possible to have the program make decisions at runtime, based on the values stored in variables. We achieve this through the use of conditional statements.

  • Classification of outcomes, such as an online symptom checker
  • Choose-your-own-adventure style games and products
  • Conditional logic is THE big difference between something like a calculator vs your computer
  • Other examples?

Operators that return boolean values

Java, like in your math classes, has the following comparison operators that all evaluate to true or false:

  • x < y
  • x <= y
  • x > y
  • x >= y

There are also ways to compare for equality and inequality:

  • x == y checks for being equal to (this is different than assignment)
  • x != y checks for being unequal

Operators that work on boolean arguments

There are also three more boolean operators in Java that both evaluate to boolean expressions and take boolean arguments:

  • the AND operator x && y returns true if both x and y are true, otherwise it returns false
  • the OR operator x || y returns true if either (or both) x and y are true, otherwise it returns false
  • the NOT operator !x is a unary operator that flips the value currently in x

These operators and expression can be combined to check complex conditions:

boolean result = (x > y)  && (!z || (x == q)); // assume these variables have all been previously defined

We can summarize this functionality with truth tables:

x y x && y x || y !x
true true true true false
true false false true false
false true false true true
false false false false true

Short-circuiting in Java

In an effort to save CPU cycles, Java will only execute clauses in an && or || if they can influence the result. For example, in the code above, if we already know that (x > y) is false, we don’t need to calculate anything after the &&. We can skip that clause; Java will do the same thing, and this is called short-circuiting.

Class participation activity 1 [5 min]

Suppose we have integer variables with values a = 1, b = 1, c = 3, d = 4, and e = 5. What do the following three expressions evaluate to?

  • ((a <= b) && (c + d > e) && (d > 1))
  • ((a > c) || ( (c + 1 < e) && (c - b > a)))
  • !((b == d - c) && (a > b) || (c < d))

if statements

Now that we can determine whether or not some expression evaluates to true or false, we can use this logic inside a conditional statement known as an if statement:

int x = 2;
int y = 3;

System.out.println("What happens below?");
if (x > y){
  System.out.println("x is bigger");
}
System.out.println("done!");

In the example above, both What happens below? and done! print, but what about the middle print statement? Because it is inside an if-block, it will only execute if the conditional associated with the if evaluates to true. Given the values of x and y, it will never print. However, if we changed these values:

int x = 3;
int y = 2;

System.out.println("What happens below?");
if (x > y){
  System.out.println("I managed to get in here, yay!");
  System.out.println("x is bigger");
}
System.out.println("done!");

All four print statement get printed; note that we can include as many statements as we like, between the curly braces, as part of the if-block.

if-else statements

What if we always want it to bring something, like a fork in the road where you must choose a path? Java has another clause, else, that you can attach to any if statement and it becomes a part of that block:

int x = Math.random(); //gets a random number
int y = Math.random();

System.out.println("What happens below?");
if (x > y){
  System.out.println("BIGGER");
} else {
  System.out.println("SMALLER");
}
System.out.println("done!");

In this example, the code will always print three lines total; the first and the last print statement, plus one and only one of either BIGGER or SMALLER. The if-else block there is considered a single unit; the else belongs to the preceeding if, and cannot exist alone.

We can therefore connect multiple if-else statements in a single block:

int x = Math.random(); //gets a random number
int y = Math.random();

System.out.println("What happens below?");
if (x > y){
  System.out.println("BIGGER");
} else if (x < y){
  System.out.println("SMALLER");
} else {
  System.out.println("EQUAL");
}
System.out.println("done!");

Here one and only one of BIGGER, SMALLER, and EQUAL are printed. This is even the case when the conditional might technically be true for multiple clauses:

int x = 13;

if (x > 10){
  System.out.println("FIRST");
} else if (x > 5){
  System.out.println("SECOND")
} else if (x == 13){
  System.out.println("THIRD")
}

The code above will only print FIRST, even though all three clauses are true when you trace it by hand (the computer won’t even check the second condition after we’ve entered the first one). Note that you don’t have to end with an else in the example above.

Nested conditionals

It’s possible to nest conditionals, as the body of each block is just code:

int x = Math.random();
int y = Math.random();

if (x > 10){
  if (y == 5){
    System.out.println("ONE");
  } else {
    System.out.println("TWO");
  }
} else {
  System.out.println("THREE");
}

Note that we use the curly braces to collect code and indicate to which if the else belongs. Having good indentation is also helpful here

Summary: what’s in our algorithm toolbox

While we have gone through some Java syntax, what’s more important going forward is what algorithmic tools we have at this point:

Operators (things we can do):

  • Variable declaration and assignment (i.e. x = 3 or x = y)
  • Mathematical operators: + - * / %
  • Boolean operators: > >= < <= == != && || !
  • Conditional statements: if-else

Data (things we can store, read, and modify):

  • User input variables (i.e. num1) – you’ll see this in the homework assignments
  • Variables we define (i.e. sum = num1 + num2)
  • Constants (i.e. 3 or 3.14 or true)

Homework 2

Let’s work on HW2 together now to apply these concepts; it is due on BB before next class.

Next class

We will continue to work on HW3 problems the next class, which will prepare you for Quiz 2.