slanted W3C logo

Day 11 — if

In today's lecture we look at the relational operators for primitive numeric types, validating user input, and Java's if statement.

Recap: boolean

A variable of type boolean can have only two values: true and false; they are used to store the result of a binary (yes/no, true/false, on/off) decision.

Relational Operators

For the primitive numeric types (int, double, etc.) the relational operators can be used to test values for equality and inequality.

Expression Meaning Value
8 < 15 8 is less than 15 true
8 > 15 8 is greater than 15 false
200L <= 300L 200 is less than or equal to 300 true
100.1 >= 100 100.1 is greater than or equal to 100 true
3 == 3 3 is equal to 3 true
1 != 2 1 is not equal to 2 true

if Statement

Java's if statement lets you choose to execute a block of code depending on a logical expression (an expression that evaluates to type boolean).


      if (logical-expression)
      {
         statement(s)
      }

Example

Suppose you work as a ride attendant at an amusement park. Your ride has a capacity of 32 people. Write a Java program that asks the user for the number of people in line waiting to get on the ride, and outputs the number of people who can safely get on the ride.

1. ask the user for a value
2. get the value
3. if the value is greater than 32
      set the value to 32
4. output the value
final int CAPACITY = 32;
output.print("Enter the number of people in line : ");
int numInLine = input.nextInt();
if (numInLine > CAPACITY)
{
   numInLine = CAPACITY;
   output.println("Busy day!");
}
output.printf("%d people can get on the ride%n", numInLine);

if Statement Braces

The braces are important! If you forget them, Java will use only the first statement after the if (logical-expression) for the statement(s) block. For example, this fragment:

int numInLine = input.nextInt();
if (numInLine > CAPACITY)
   numInLine = CAPACITY;
   output.println("Busy day!");
output.printf("%d people can get on the ride%n", numInLine);

is equivalent to this fragment:

int numInLine = input.nextInt();
if (numInLine > CAPACITY)
{
   numInLine = CAPACITY;
}
output.println("Busy day!");
output.printf("%d people can get on the ride%n", numInLine);

Why Do We Care About Blocks?

The if statement injects a block into your code.

public class BlockExample1
{
   public static void main(String[] args)
   {
      PrintStream output = System.out;
      Scanner input = new Scanner(System.in);

      float userValue = input.nextFloat();

      if (userValue < 0f)
      {
         float absValue = -userValue;
      }

      // error! absValue is out of scope
      float signum = userValue / absValue;
   }
}

To fix the above example, you need to move the declaration of absValue outside and before the if statement.

      float absValue = userValue;
      if (userValue < 0f)
      {
         absValue = -userValue;
      }

if-else

An if-else statement diverts program flow into two separate blocks.


      if (logical-expression)
      {
         statement(s)
      }
      else
      {
         statement(s)
      }

If the logical-expression is true then program flow goes to the purple block; otherwise program flow goes to the orange block.

Example

In Ontario, most hourly employees earn overtime pay after they have worked 44 hours in a work week. Overtime time is 150% of the employee's regular rate of pay. Write a program that calculates both the regular-time pay and the overtime pay.

   if the number of hours worked > 44
      regular pay = 44 * hour wage
      overtime pay = (number of hours worked - 44) * 
                     hourly wage * 1.5
   else
      regular pay = number of hours worked * hourly wage
      overtime pay = 0
      final double FULL_WEEK = 44.0;
      final double OVERTIME_RATE = 1.5;
      double regularPay;
      double overtimePay;
      if (hours > FULL_WEEK)
      {
         regularPay = FULL_WEEK * hourlyWage;
         overtimePay = (hours - FULL_WEEK) *
                       hourlyWage * OVERTIME_RATE;
      }
      else
      {
         regularPay = hours * hourlyWage;
         overtimePay = 0.0;
      }

Why are the variables regularPay and overtimePay declared before the if-else statement?

Can you rewrite Step 5 using only an if statement?

Multiway Branching

Suppose you want to compare the magnitude of two fractions f and g such that:

if f > g
   value = 1
else if g > f
   value = -1
else
   value = 0

Notice that there are now 3 possible paths your code can take.

double fMag = (double) f.getNumerator() / f.getDenominator();
double gMag = (double) g.getNumerator() / g.getDenominator();

int value;
if (fMag > gMag)
{
   value = 1;
}
else if (gMag > fMag)
{
   value = -1;
}
else
{
   value = 0;
}

* Or you could just delegate to Fraction:

int value = f.compareTo(g);

Logical (or Boolean, or Conditional) Operators

Suppose you were writing a program where you needed to find the minimum of three unique real numbers stored in variables eig1, eig2, and eig3.

if (eig1 is less than eig2) AND (eig1 is less than eig3)
   min = eig1
else if (eig2 is less than eig1) AND (eig2 is less than eig3)
   min = eig2
else
   min = eig3

Logical (or Boolean, or Conditional) Operators

If a condition depends on two expressions being true you would use the Conditional-AND operator && to combine the two expressions:

      if ((eig1 < eig2) && (eig1 < eig3))
      {
         min = eig1;
      }
      else if ((eig2 < eig1) && (eig2 < eig3))
      {
         min = eig2;
      }
      else
      {
         min = eig3;
      }

Java evaluates the boolean expressions from left to right. For Conditional-AND, if the boolean expression on the left hand side is false, Java does not evaluate the boolean expression on the right hand side.

Logical (or Boolean, or Conditional) Operators

If a condition depends either of two expressions being true you would use the Conditional-OR operator || (two vertical bars) to combine the two expressions.

For example, suppose you are the quality control engineer at a food packaging plant. Your packaging machine is supposed to fill packages with a certain weight of product, and you need to reject packages that are too light or too heavy.

if (weight < target weight) OR (weight > target weight)
    reject package
      final double TARGET_WEIGHT = 500;
      if ((weight < TARGET_WEIGHT) || (weight > TARGET_WEIGHT))
      {
         output.println("Rejected!");
      } 

Java evaluates the boolean expressions from left to right. For Conditional-OR, if the boolean expression on the left hand side is true, Java does not evaluate the boolean expression on the right hand side.

A Puzzle

Think of a positive whole number, and apply the following rules:

  1. if the number is even, divide it by 2
  2. if the number is odd, multiply it by 3 and add 1
  3. if you reach 1, stop; otherwise go to Step 1

Do you always reach 1? Prove your answer.