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

Write a program that prompts the user for a number, and then outputs the absolute value of the number.

import java.io.PrintStream;
import java.util.Scanner;

public class AbsoluteValue
{
   public static void main(String[] args)
   {
      PrintStream out = System.out;
      Scanner in = new Scanner(System.in);
      
      out.print("Enter a number: ");
      double value = in.nextDouble();
      
      double absolute = value;
      if (value < 0.0)
      {
         absolute = -value;
      }
      
      out.printf("The absolute value of %f is %f%n",
                 value, absolute);
   }
}

You probably should use Math.abs in this case.

Example

Write a program that prompts the user for an integer value, and then outputs the parity (even or odd) of the value.

import java.io.PrintStream;
import java.util.Scanner;

public class EvenOdd
{
   public static void main(String[] args)
   {
      PrintStream out = System.out;
      Scanner in = new Scanner(System.in);
      
      out.print("Enter an integer: ");
      int value = in.nextInt();
      
      String parity = "even";
      if (value % 2 != 0)
      {
         parity = "odd";
      }
      
      out.printf("The number %d is %s%n",
                 value, parity);
   }
}

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

Write a program that prompts the user for an integer value, and then outputs the parity (even or odd) of the value.

import java.io.PrintStream;
import java.util.Scanner;

public class EvenOdd2
{
   public static void main(String[] args)
   {
      PrintStream out = System.out;
      Scanner in = new Scanner(System.in);
      
      out.print("Enter an integer: ");
      int value = in.nextInt();
      
      String parity = null;
      if (value % 2 == 0)
      {
         parity = "even";
      }
      else
      {
         parity = "odd";-
      }
      
      out.printf("The number %d is %s%n",
                 value, parity);
   }
}

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);

Example

Write a program that prompts the user for two fractions and outputs whether the first fraction is smaller than, equal to, or greater than the second fraction.

import java.io.PrintStream;
import java.util.Scanner;
import type.lib.Fraction;

public class FractionCompare
{
   public static void main(String[] args)
   {
      PrintStream out = System.out;
      Scanner in = new Scanner(System.in);
      
      out.print("Enter the first fraction: ");
      long num = in.nextLong();
      long den = in.nextLong();
      Fraction first = new Fraction(num, den);
      
      out.print("Enter the second fraction: ");
      num = in.nextLong();
      den = in.nextLong();
      Fraction second = new Fraction(num, den);
      
      int compare = first.compareTo(second);
      String msg = null;
      if (compare < 0)
      {
         msg = "smaller than";
      }
      else if (compare == 0)
      {
         msg = "equal to";
      }
      else
      {
         msg = "greater than";
      }
      
      out.printf("%s is %s %s%n",
                 first, msg, second);
   }
}

Logical (or Boolean, or Conditional) Operators

There are only 3 logical operators that can be applied to boolean values:

      boolean a;
      boolean b;

      /* some code here that assigns values to a and b */
Operator Name Example Meaning
AND a && b true only if both a and b are true
OR a || b true if either a and b are true
NOT !a true if a is false and false if a is true

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 x1, x2, and x3.

if (x1 is less than x2) AND (x1 is less than x3)
   min = x1
else if (x2 is less than x1) AND (x2 is less than x3)
   min = x2
else
   min = x3

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 ((x1 < x2) && (x1 < x3))
      {
         min = x1;
      }
      else if ((x2 < x1) && (x2 < x3))
      {
         min = x2;
      }
      else
      {
         min = x3;
      }

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.