3. Conditions

3.1. Learning Outcomes

3.2. Key Terms

Review important terms.

3.3. Resources

3.4. Overview

In real life, we often encounter situations where we need to make decisions based on certain conditions. For example, based on the student numerical grade we want to determine whether the student is passing or failing the class.

So far, the programs we have been writing do not support different outcomes such as determining whether a student is passing or failing. They do not support computations that depend on the conditions, and they cannot validate user input. Our programs need to produce different results based on conditions encountered in the program.

In this chapter we introduce the boolean data type, a primitive type that can hold true or false. We discuss relational and logical operators and build an understanding of boolean expressions (conditions), and introduce conditional statements in Java (if, switch and the ternary expression).

By the end of this chapter, you should be able to use boolean expression and conditional statement effectively to solve common programming problems. It is important to note that the terms boolean expression and condition are used interchangeably throughout this chapter.

3.5. Relational Operators, Simple Boolean Expressions and the boolean Data type:

We will start this section by introducing the boolean data type. A variable of boolean data type can have only one of two values, either true or false. The example below shows how to declare and initialize a boolean data type:

boolean x; 
x = true; 

Or alternatively, the two steps can be combined in one statement as below:

boolean x = true; 

Relational operators are used to check conditions. They can be used to check whether two values are equal, not equal, greater than or less than, the table below list the java different relational operators along with their mathematical equivalent operators, the result of an operational operator is either true or false (boolean):

Table 3. Relational Operators

Java Mathematics
== =
!=
> >
< >
>=
<=

Note: == is used to check for equality

Boolean expressions use relational operators to check conditions and to compare variables against certain values. For example, in order for a student to pass a class his grade must be greater than or equal to 70; that is, we need to compare the student grade with 70. The boolean expression (condition) that represents this comparison is grade >= 70. A boolean expression will evaluate to either true or false. The figure below shows some examples of boolean expressions:

int i = 5;
int j = 10;
boolean b;
i == j; //Evaluates to false, because i is not equal to j
i < j;  //Evaluates to true, because i is less than j
i <= j; //Evaluates to true, because i is less than or equal to j

b = i > j; //the value assigned to b is false
b = i != j; //the value assigned to b is true
b = j >= i; //the value assigned to b is true

3.6. Logical Operators and Compound Boolean Expressions

Sometimes we need to check for two or more conditions in order to decide or pick an execution path. Logical operators allow us to combine two more conditions. A compound boolean expression consists of two or more boolean expressions joined with logical operators. For example, assume we have a class x that requires two prerequisites class A and class B, in order to decide whether a student can register for class x or not, we need to verify that the student has passed both class A and class B. In this section we will cover the logical and operator (&&), the logical or operator (||), the logical negation (not) operator (!) and exclusive or operator "XOR" (^). the four logical operators with their Java symbols are shown in the table below, and, or and exclusive or are binary operators, that is they take two operands while not is a unary operator, that is, it has only one operand:

Table 4. Logical Operators

Logical Operator Java Symbol
and &&
or ||
not !
XOR ^

The table below shows the truth table for &&, ||, ^ and !, where b1 and b2 stands for boolean expression 1 (condition1) and boolean expression 2 (condition2), respectively:

Table 5: Truth Table

b1 b2 b1 && b2 b1 || b2 b1 ^ b2 !b1
true true true true false false
true false false true true false
false true false true true true
false false false false false true

Referring to the table above we notice the following:

Below are examples of compound boolean expressions:

int i = 5;
int j = 10;
int k = 15;

//&&
i < j && j < k; //true: both i < j and j < k are true
i > j && j < k; //false: i > j is false
i < j && j < k; //false: j > k is false
i > j && j < k; //false: both i > j and j > k are false

//||
i < j || j < k; //true: both i < j and j < k are true
i > j || j < k; //true: j < k is true
i < j || j > k; //true: i < j is true
i > j || j > k; //false: both i > j and j > k are false

//^
i < j ^ j < k; //false: both i < j and j < k are true
i > j ^ j < k; //true: i > j is false and j < k is true
i < j ^ j > k; //true: i < j is true and j > k is false
i > j ^ j > k; //false: both i > j and j > k are false

//!
!(i < j); //false: i < j is true
!(i > j); //true: i > j is false

Java use short circuit evaluation for both && and || operators. In the case of &&, if the first boolean expression (condition) evaluates to false, the result of && is false regardless of whether the second boolean expression evaluates to true or false. In the case of ||, if the first boolean expression (condition) evaluates to true, the result of || is true regardless of whether the second boolean expression evaluates to true or false. To better understand short circuit analysis, assume we have two boolean expressions b1 and b2. In the case of && (b1 && b2), assume b1 is false, java will not evaluate b2 since, since b1 && b2 is false regardless the value of b2. In the case of || (b1 || b2), assume b1 is true, java will not evaluate b2 since, since b1 || b2 is true regardless the value of b2.

3.7. Operator Precedence

The table below show the operator Precedence from highest to lowest:

Table 6: Operator Precedence

Precedence
var++, var−−
Unary +, Unary −, ++var, −−var
!
*, / , %
+ (addition), − (subtraction)
<, <=, >, >=
^
&&
||
=, +=, −=, *=, /=, %=

3.8. if Statement

In the introduction section, we presented the problem of determining whether a student is passing a class or not based on the student numerical grade; assuming a passing grade of 70, a student is passing the class if his/her grade is greater than or equal to 70. The java if statement is needed to solve this problem. In this section, we will introduce if, if-else, nested if, and multibranch if-else statements.

3.8.1. if Statement

The general syntax for an if statement is java is:

if (boolean expression/condition) {
	Statement1;
	Statement2;
	.
	.
	.
}

The statements inside the if block are executed only if the boolean expression evaluates to true, otherwise the entire block will be skipped. Notice that, the curly braces ({}) are needed only if we have more than one statement that need to be executed if the boolean expression evaluates to true.

Example 1: Write a program that prompts the user to enter his grade, the program evaluates the grade and prints Passing if the student is passing the class and prints Not Passing if the student is not passing the class.

Step-by-Step Execution for the program below

//This program prompts the user to enter his grade
//Based on the entered grade the program will print
//passing or not passing
import java.util.Scanner;

public class CheckGrade{
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter your grade: ");
    double grade = in.nextDouble();
    if (grade >= 70){
      System.out.println("Passing");
    }
    if (grade < 70){
	System.out.println("Not Passing");
    }
  }
}

Example 2: Write a program that prompts the user for an integer value and then prints if the entered value is odd or even.
Step-by-Step Execution for the Program Below

/*
This program prompts the user to enter an integer
and prints if it is odd or even
% is used to determine whether the integer is odd or even
*/

import java.util.Scanner;

public class OddEven{
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter an integer value: ");
    int i = in.nextInt();
    if (i % 2 == 0){
      System.out.println(i + " is an even number.");
    }
    if (i % 2 != 0){
      System.out.println(i + " is an odd number.");
    }
  }
}
		

Example 3: Write a program that reads a student numerical grade and prints the letter grade of the student, grade >= 90, prints A, 90 > grade >= 80, prints B, 80 > grade >= 70, prints C, 70 > grade >= 60, prints D, grade < 60, prints F. This example illustrates the use of compound boolean expressions.

Step-by-Step Execution of the Program Below

/* This program prompts the user to enter his grade
Based on the entered grade the program will print
letter garde, A, B, C, D, or F */
import java.util.Scanner;

public class LetterGrade{
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter your grade: ");
    double grade = in.nextDouble();
    if (grade >= 90)
      System.out.println("Your letter grade is A");
    if (grade < 90 && grade >= 80)
      System.out.println("Your letter grade is B");
    if (grade < 80 && grade >= 70)
      System.out.println("Your letter grade is C");
    if (grade < 70 && grade >= 60)
      System.out.println("Your letter grade is D");
    if (grade < 60)
      System.out.println("Your letter grade is F");
  }
}

3.8.2. if-else Statement

Considering example 1 above, we notice that there is no need to evaluate the boolean expression again, since a student can only be passing or not passing. Checking the first boolean expression is enough to decide whether the student is passing or not passing, Therefore, evaluating the second boolean expression is not needed. The same discussion is applicable to second example. To avoid redundant evaluations java introduces an if-else statement. The general syntax for an if-else statement is java is:

if (boolean expression/condition) {
	Statement/statements if boolean expression evaluates to true;
} else{
	Statement/statements if boolean expression evaluates to false;
}

Note: There is no boolean expression that follow else.

The statements inside the if block are executed only if the boolean expression evaluates to true, otherwise the statements in the else block will be executed.

Example 4: rewrite the program from example 1 using an if-else statement instead of two if statements, the program prompts the user to enter his grade and will print either, he is passing the class, or he is not passing the class.

Step-by-Step Execution of the Program Below

//This program prompts the user to enter his grade
//Based on the entred grade the program will print
//passing or not passing
import java.util.Scanner;

public class CheckGradeV2{
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter your grade: ");
    double grade = in.nextDouble();
    if (grade >= 70)
      System.out.println("Passing");
    else
      System.out.println("Not Passing");
  }
}

Example 5: rewrite the program from example 2 using an if-else statement instead of two if statements, the program that prompts the user for an integer value and then prints if the value is odd or even.

Step-by-Step Execution of the Program Below

//This program prompts the user to enter an integer
//and prints if it is odd or even
// % is used to determine whether the integer is odd or even
import java.util.Scanner;
public class OddEvenV2{
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter an integer value: ");
    int i = in.nextInt();
    if (i % 2 == 0)
      System.out.println(i + " is an even number.");
    else
      System.out.println(i + " is an odd number.");
  }
}

3.8.3. Multi-branch (Cascaded) if Statement

In example 3, we wrote a program that read a student’s numerical grade and printed the letter grade. Analyzing the program, we found, even though we know the assigned letter grade, we continued checking the subsequent conditions. For example, if the student grade was 90, evaluating the first boolean expression (grade >= 90) will result in letter grade of A and we should stop, however, we noticed that the program will continue evaluating other subsequent statements. These subsequent evaluations are unnecessary. To avoid such redundancy, a multibranch if statement (if – else if – else) can be used. Example 6 shows the solution for example 3 using a multibranch if statement. It is important to note that only one branch of the multibranch if statement is executed. The general syntax for a multi-branch (cascaded) if statement in java is:

If (boolean expression1) {
	Statement/statements;
}
else if(boolean expression2){
	Statement/statements;
}
else if (boolean expression3){
	Statement/statements;
}
.
.
else{
	Statement/statements;
}

Example 6: revisiting example 3, Write a program that reads a student numerical grade and prints the letter grade of the student, grade >= 90, prints A, 90 > grade >= 80, prints B, 80 > grade >= 70, prints C, 70 > grade >= 60, prints D, grade < 60, prints F.

Step-by-Step Execution of the Program Below

//This program prompts the user to enter his grade
//Based on the entered grade the program will print
//letter grade, A, B, C, D, or F
import java.util.Scanner;

public class LetterGradeV2{
  public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter your grade: ");
    double grade = in.nextDouble();
    if (grade >= 90)
      System.out.println("Your letter grade is A");
    else if (grade >= 80)
      System.out.println("Your letter grade is B");
    else if (grade >= 70)
      System.out.println("Your letter grade is C");
    else if (grade >= 60)
      System.out.println("Your letter grade is D");
    else
      System.out.println("Your letter grade is F");
  }
}

3.8.4. Nested if Statement

A nested if statement is an if statement that embedded inside another if or else statement. The general syntax for a nested if statement in java is:

if (boolean expression1) {
	//executes if boolean expression1 evaluates to true
	if (boolean expression2){
		statement/statements to be executed if boolean expression2 is true;
}
}

Example 7: Write a program that reads an integer, and prints “You Won!!!” if the entered value is between 50 and 100 inclusive.

Step-by-Step Execution of the Program Below

/* This Program prompts the user to enter an integer value
 * and prints "You Won!!!" if the entered value is between
 * 50 and 100 inclusive.
 */
import java.util.Scanner;
  public class NestedIfExample{
    public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    System.out.print("Please enter an integer: ");
    int i = in.nextInt();
    if (i <= 100)
      if (i >= 50)
        System.out.println("You Won!!!");
    }
  }

3.9. switch Statement

A switch statement is multi-branch statement, in which the execution path is based on a value of a variable or an expression. Based on the java documentation, the expression or the variable can be byte, short, char and int primitive data types. In addition, it works with String, Character, Byte, Short, Integer, etc. Unlike the if statement, a switch statement can have several execution paths. The Syntax for the switch is shown below, where x and y are values and are not variables. Note that having a default block is optional:

switch(expression) {
	case x:
		statement/statements
		break;
	case y:
		statement/statements
		break;
	.
	.
	default:  //optional
		statement/Statements
}

The switch statement works as follows:

Example 7: Write a program that reads the year and month as integers and print the number of days in the entered month. You can assume 1 for January, 2 for February, and so on.

Solution: For January, March, May, July, August, October and December (months 1, 3, 5, 7, 8, 10, 12) all have 31 days. For April, June, September and November (months 4, 6, 9, 11) all have 30 days. For February (month 2) will depend on the year. If the year is leap, it will have 29 days otherwise it will have 28 days.

Step-by-Step Execution for the Program Below

/*
This program prompts the user for the month and the year
and prints the number of days in the entered months
Month and year should be entered as integer
*/
import java.util.Scanner;
public class NumberOfDaysInMonth{
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    //read year as integer
    System.out.print("Please enter year: ");
    int year = in.nextInt();
    //read month
    System.out.print("Please enter a month 1 - 12: ");
    int month = in.nextInt();
    switch (month) {
      case 1:
      case 3:
      case 5:
      case 7:
      case 8:
      case 10:
      case 12:
        System.out.println("Number of days of month " + month + " is " + 31);
        break;
      case 4:
      case 6:
      case 9:
      case 11:
        System.out.println("Number of days of month " + month + " is " + 30);
        break;
      case 2:
        if (((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0))
           System.out.println("Number of days of month " + month + " is " + 29);
        else
          System.out.println("Number of days of month " + month + " is " + 28);
        break;
      default:
        System.out.println("Invalid month.");
        break;
        }
    }
}

3.10. Summary

In this chapter, we covered the boolean datatype which can store true or false values. We also learned about the relational operators (<, <=, >, >=, ==, !=) and studied boolean expressions the yield either true or false. We also studied the logic operator (&&, ||, ! and ^) and how they are used to combine boolean expressions (conditions) to produce compound boolean expressions. Then we studied the if statement and discussed the need for this statement to write programs that allow us to make decisions based on certain criteria. Finally, we covered the switch statement.

3.11. Exercises/Problem Solving:

Group 1: Exercise 1-7 of Section 5.11 of Think Java PDF or read the problem descriptions online at Section 5.11

Group 2:

3.11.1 Exercise 1

Write a program that generates a random integer between 0 and 10 and ask the user to guess the generated number. if the user enters the correct number, the program will print Hooray you guessed the number. Otherwise the program prints You Lost!!. Hint: you can use Math.random() to generate a random number as follows:

int rand = (int)(Math.random() * 11);

3.11.2 Exercise 2

Write a program that prompts the user to enter the radius of a circle and calculates the area for that circle. The program should check the entered number. if the entered number is negative, the program prints Invalid Entry, the radius should be positive and quits. Otherwise, the program should calculate the area of the circle and prints The area of a circle with radius "the radius value entered by the user" is "The calculated value of the circle area". (Hint: Circle area = π × radius × radius)

3.11.3 Exercise 3

Write a program the reads three integers from the user and prints the largest number.

3.11.4 Exercise 4

Write a program that prompts the user to enter a number and check the following:

3.11.5 Exercise 5

Write a program that prompts the user to enter the day of the week as an integer between 1 and 7, for Sunday through Saturday, and prints weekday for entries 1 through 5 inclusive, and weekend for 6 and 7. for all other entries, the program prints invalid weekday.

3.11.6 Exercise 6

Write a program to calculate the cost of car insurance based on the driver age and number of accidents. The base insurance cost is $300. if the driver age is below 27, there is a surcharge of $100. the additional surcharge for accidents is shown below:

Surcharge Per Accidents

Number of accidents Surcharge
1 $100
2 $150
3 $250
4 or more $1000

3.11.7 Exercise 7

Write a Program that prompts the user to enter four integers and prints them in alphabetical order.

3.11.8 Exercise 8

Write a program that prompts the user to enter the length of the three edges of a triangle. The program calculates the perimeter of the triangle if the input is valid, otherwise it prints invalid input. The input is valid if the sum of every pair of two edges is greater than the remaining edge.

3.11.9 Exercise 9

Write a program that computes and interprets the Body Mass Index (BMI). The program prompts the user to enter his/her weight in pounds and his/her height in inches. the program then calculates the bmi using the formula: BMI = Weight(kilograms)/(height(meters))2. To convert weight in pounds(p) to kilograms(kg) use the formula: weight(kg) = weight(p) * 0.4536. To convert inches(in) into meters(m) use the formula: height(m) = height(in) * 0.0254. The BMI interpretation is as follows:

BMI Interpretation

BMI Interpretation
BMI < 18.5 Underweight
18.5 ≤ BMI < 25.0 Normal
25.0 ≤ BMI < 30.0 Overweight
BMI ≥ 30.0 Obese

3.12. Do You Have Any Questions about Chapter 3?

Comments