Lesson 3 - Conditional Logic

TABLE OF CONTENTS: Introduction - Section 1: Boolean Logic - Section 2: Conditional Logic - Section 3: Applying it to programs

Introduction -

You've started writing some simple programs in our previous lessons. Now it's time to have those programs make decisions for themselves. We don't expect these programs to become self-aware, they're only going to make the decisions that we teach them to, using the rules that we code them with. Conditional Logic is the term for making a decision based on a certain condition(s).

All of these are decisions that you can program a computer to make over and over. Computers are good at making repetitive tasks easier.

Good Luck! Your programs will be much more powerful and interesting after you complete this lesson.

Pre-requisites -

Before beginning this lesson you should have completed the HelloWorld2 program.  (This would give you experience using the programming environment and structuring simple programs.) You should also have a basic understanding of objects and variables (although not mastery yet.) 

Goals -

  1. Students will be able to determine the outcome of a Boolean logic statement. 
  2. Students will use correct syntax when writing conditional logic statements in java. 
  3. Students will be able to use conditional logic statements within Java programs to make decisions and accomplish tasks.

Section 1: Boolean Logic

These are your objectives for this section:

Given a set assignment statements to define variables and a series of simple (one step) Boolean logic statements involving those variables students will correctly identify the result of the Boolean logic as true of false. 

Given a series of compound (involving and/or) Boolean logic statements, students will correctly simplify them into true or false. 

Boolean logic is a system that evaluates expressions into either true or false. This makes it very useful in programming.

It is a decision making system: true or false / yes or no / one or zero.

You've worked with Boolean logic before, but probably never called it that.

3 > 4 = false
2 < 8 = true

Those are Boolean logic statements. They consist of an expression that can be evaluated into true or false.

Here is a list of the Boolean operators that we will use in this class:

operator description examples
> greater than 5 > 7 = false
100 > 99 = true
< less than 10 < 20 = true
10 < 8 = false
>= greater than or equal to 1 >= 2 = false
1 >= 1 = true
<= less than or equal to 1 <= 2 = true
1 <= 1 = true
== equal to (yes, it's two equals signs) 7 == 6 = false
3 == 3 = true
!= not equal to 7 != 6 = true
3 != 3 = false

These Boolean operators deal with numeric values or variables (of type int or double). Later we will also learn some methods that return Boolean values.

Consider the following variable declarations:

int num = 10; 
int x = 4; 
int z = 14;

What would be the result of evaluating the following expressions?

x > 0
x >= z
num != 10
x != 3
x+num == z
z <= 99
num < 1
z > z
8 < x

Drag the mouse over the second row to check your answers.


Boolean logic also allows us to look at a combination of conditions in an expression.

description examples
Both items must be true...
true && true = true
true && false = false
false && true = false
false && false = false
OR (The pipe, | is shift-backslash)
One or the other (or both) need to be true...
true || true = true
true || false = true
false || true = true
false || false = false
NOT (exclamation point!)
Opposite if an expression...
!true = false
!false = true

Using our same declarations from above, we could make compound statements like:

( x > 5 ) && ( num == 10 )

Here, the first part is false and the second part is true, since they are combined with an AND operator both must be true, so this would evaluate to false.

( x > 5 ) || ( num == 10 )

However in this case since the two parts are connected with an OR operator, only one or the other need to be true, so this would evaluate to true.

Next we will learn how to use this type of logic to make decisions within our Java code.

Section 2: Conditional Logic in Java

These are your objectives for this section:

Given an output description and a section of code with a missing line, students will be able to fill in a conditional logic statement that would accomplish the task without producing errors. 

Given a description of three possible outcomes based on the numeric value of an Integer variable, students will write a series of conditional logic statements to successfully choose the correct outcome. 

Given sections of code that includes a conditional logic statement, students will identify and correct the error in the code or identify the code as correct.  Possible errors to be tested would include – conditions on else statements, proper use of {} to group statements, proper use of Boolean operators, choice of == vs. .equals() based on the types of objects being compared, improper nesting of statements, syntax errors. 

Now that you have learned about Boolean logic you have an understanding of how to determine if an expression is true or false.

In Java, we can write statements that will only be executed if a condition is true. Here is how this would work.


The statement would only be run if the condition evaluated to true.

if(score > 100)
    System.out.println("You Win!");

In this example, if the variable score was greater than 100, the terminal window would display You Win!, however if the score was not above 100, the program would continue without printing out You Win!

Sometimes you have multiple lines of code that you want to execute conditionally. You can always group together sections of code using curly brackets { }.

if(score > 100)
     System.out.println("You Win!");
     gamesWon = gamesWon + 1;
     score = 0; //Reset the score

This example (above) of code would run all three statements within the curly brackets only if the condition was met. However, the example below would only decide whether or not to execute the "You Win!" line of code, the others would always run because they are not grouped with the if statement. Remember unless you use curly brackets, the if statement ends at the semicolon.

if(score > 100)
     System.out.println("You Win!");
     gamesWon = gamesWon + 1;
     score = 0; //Reset the score

Java also provides a way to have code that executes when a condition is false. To do this you would use an else statement. Else statements must always follow an if statement. They work in tandem. The if statement tells what to do if the condition was true, the else statement tells what to do if the condition is false.

   statement; //Runs if the condition is true.
   statement2; //Runs if the conditions is false.

Note that an else statement NEVER has a condition. The if statement contains the decision, the else statement only contains the alternative reaction (when it's false.)

In the context of the earlier example you might write:

if(score > 100)
    System.out.println("You Win!");
    System.out.println("You Lose.");

The same rules for using curly brackets to house multiple statements applies to the else statement as well.

Sometimes you might have a series of conditions that you wish to check. This might be done with a series of if statements, or more often the best choice is if - else if - else. In the example below, you check to see if the student earned an "A", but if they didn't, within the else statement you check another condition (else if) to see if they got a "B" this continues until the final else, they got an "F".

if(grade > 90)
else if (grade > 80)
else if (grade > 70)
else if (grade > 60)

One important thing to note is that there are many ways that you could code the decision process shown above that would work.

Some special (or new to you) cases for the conditions within if statements.

The computer really isn't that smart. It knows how to deal with numbers, because those are primitive types of variables. The computer can easily tell if an int variable is equal to 5. However once you go beyond the few primitive types, the computer doesn't really know how to compare things. For example if I enter my name into a String variable and checked if(name=="Mike") the result would be false (even if my name was Mike). The computer doesn't know the details of what is stored in a String object, so it doesn't know how to compare two of them.

There is a solution. When programmers created the String class, they wrote a method called .equals( ). This method receives a String and compares it to the one calling the method and returns either true or false. Let me show you an example...

String name = "Mike"
    System.out.println("Access Granted");
    System.out.println("Access Denied");

The String object (name) calls the equals method to compare itself to "Mike" and returns either true or false. The result of this method call is generated and then the if statement can make it's decision.

We will see other Boolean methods for use in comparing objects as we continue in this course, but the .equals method is one that will be of great use to us early in this course.


Try some example coding challenges below. You can check your work by highlighting the answer section.

Write a section of code that would print out Good Job if the value of the int grade was higher than 80.
if(grade > 80) 
   System.out.println("Good Job");
Write a section of code that adds one to a variable, counter, only if the value of counter is less 100, otherwise reset it to zero.
    counter = counter + 1;
    counter = 0;
Write a section of code that checks a String variable password against a String called key and replies "You are in" if the password matches the key.
    System.out.println("You are in");
Write the conditional logic for a guess number game. Given an integer variable guess, and an integer variable secretNumber, respon to the user whether they are "Too high", "Too low" or "Just right"
if(guess > secretNumber)
    System.out.println("Too high");
else if (guess < secret Number)
    System.out.println("Too low");

    System.out.println("Just right");

Find and correct the errors in the following pieces of code:

if(number = 5) 
if(number == 5) //Two equals signs to compare.
String code = "asdf";
if(code == "asdf")
    System.out.println("You Win");
String code = "asdf";
if(code.equals("asdf")) //Must use .equals() here
    System.out.println("You Win");
if(score > 100)
else (score <= 100)
if(score > 100)
else //No conditions on else statements

Section 3: Applying conditional logic to programs

This is your objective for this section:

Given a specification and computer access with appropriate software, write a program that produces the correct output (e.g. a letter grade) based on a user input (e.g. percentage score).  The program must run without errors and produce the correct output in every possible test case (e.g. 0-100%)

Now you know the basics about conditional logic, so let's write a program!

For this example, we will continue one of the examples that we looked at in the previous section. We will have the user enter a percentage grade and we will tell them what letter grade to give. We'll use the same scale as in the example above. (90=A, 80=B, 70=C, 60=D.) What we need to do is combine the snippets of code into a runnable program.

public class gradeConverter
    public static void main(String[] args)   
        //Declare a scanner object to get input.
        Scanner keyboard = new Scanner(System.in);

        //Get the grade from the user.
        System.out.println("Enter a percentage grade.");
        int grade = keyboard.nextInt();

        //Start the output line (print, not println).
        System.out.print("The letter grade is: ");

        //Determine and print the proper grade.
        if(grade > 90)
        else if (grade > 80) 
        else if (grade > 70)
        else if (grade > 60)

Here are a few programming challenges for you to try:

(This assignment is worth 90 points. You must complete three of the following programs)

  1. Write a program that asks the user for a month, and then displays the number of days in that month.
  2. Advanced** Write a program that asks the user for a day, month and year and displays what day of the week that was. (This will require some investigation on the Internet. There is a formula for this.)
  3. Write a program that reads a pair of numbers and then prints the numbers out in numerical order. (**Try it with three or four numbers!)
  4. Write a program that receives the three coefficients of a quadratic equation and prints out the two solutions. You program should print out NO SOLUTIONS if that is the case. (You'll have to make sure the value under the square root is not negative.)


Helpful References


Java Au Naturel

Java API

Online Tutorial - LandOfCode

Online Java Tutorial - Cafe Au Lait

Text - Java Concepts by Cay Horstmann (Chapter 6 - Decisions) *We have six copies of this book in the computer lab*