Conditionals

As we write more complicated programs, we don’t always want them to do the same thing in all cases. We might want them to do one thing in one situation, and another thing in a different one. For example, a computer game does one thing while the game is in progress, but behaves differently when the game is over.

In this chapter, we will look at several kinds of conditional statements that will allow us to different things in different situations.

Subsections of Conditionals

If Statements

An if statement allows us to do something only if some condition is true.

If statement syntax

Here is the syntax for an if statement:

if (condition) 
{
    //statements
}

Here, condition is either a boolean variable or an expression that evaluates to true or false. The statements inside the if- tatement are things that we ONLY want to happen if our condition is true. Finally, the brackets {} around the body are optional if there is only one statement inside.

If statement example

For example, suppose we want to get the user’s name and age as input. In any case, we want to then print out a greeting. We also want to print “You are an adult” if the user is 18 or older.

Here is the full program:

import java.util.*;
public class HelloAdult 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter your name: ");
        String name = s.nextLine();

        System.out.print("Enter your age: ");
        int age = s.nextInt();

        System.out.printf("Hello, %s%n", name);
        if (age >= 18) 
        {
            System.out.println("You are an adult");
        }
    }
}

When the program runs, it will ask the user for their name and age and read those values into the name and age variables. It will then print Hello and the person’s name. Finally, if the person is 18 or older, the program will print “You are an adult”. If the user is under 18, the program will not print the “You are an adult” line.

If...Else Statements

An if…else statement allows us to do one thing if a condition is true, and a different thing if the condition is not true.

If…else statement syntax

Here is the syntax of an if…else statement:

if (condition)
{
    // first set of statements
}
else
{
    //second set of statements
}

Here, we will check condition – if it is true, we will execute the first set of statements. If condition is false, we will execute the second set of statements. In any case, exactly one set of statements is executed.

If…else example

For example, suppose we want to print out whether a number is even or odd. We can tell if a number is even by checking to see if it is divisible by two (i.e, we can use the modulo operator, %, to see if the remainder of a number when dividing by two is 0).

Scanner s = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = s.nextInt();

//If the remainder of num/2 is 0, then num is even
if (num % 2 == 0) 
{
    System.out.printf("%d is even%n", num);
}
else 
{
    System.out.printf("%d is odd%n", num);
}

(Note: this is not a complete program. We would need to put this code inside a class declaration and inside the main method.) When this code is executed, it will first ask the user for a number, and store the result in the num variable. It will then compute num%2 (the remainder of num/2). If it is 0, then it will print that the number is even. If it is anything else, it will print that the number is odd. Each time, exactly one of the statements will be printed.

If...Else If Statements

An if…else if statement allows us to do differently things for several cases.

If…else if statement syntax

Here is the syntax for an if…else if statement:

if (condition1) 
{
    //first set of statements
}
else if (condition2) 
{
    //second set of statements
}
...
else 
{
    //last set of statements
}

In this structure, we first evaluate condition1. If it is true, then we execute the first set of statements and leave the if…else if statement. If condition1 is false, then we step down and evaluate condition2. If it is true, then we execute the second set of statements and move on in the program. If it is false, we move down to evaluate the next condition. This process continues until we run out of conditions to check. If none of the conditions were true, then the statements inside the else are executed.

We can have as many “else if” conditions as we want in this structure (which is denoted by the …). Furthermore, the else" portion is optional – we don’t have to have a special section that executes if none of the conditions were true.

If…else if example 1

For example, suppose we want to print out an age category for the user:

Scanner s = new Scanner(System.in);
System.out.print("Enter your age: ");
int age = s.nextInt();

if (age <= 12) 
{
    System.out.println("You are a child");
}
else if (age < 19) 
{
    System.out.println("You are a teenager");
}
else 
{
    System.out.println("You are an adult");
}

In this example, exactly one of the statements will be printed, depending on the user’s age.

If…else if example 2

As another example, suppose you want to ask the user for 5 tests grades (out of 100) so that you can calculate their overall letter grade (90% and up is an A, 80-90% is a B, etc.) Here is a fragment of the program:

Scanner s = new Scanner(System.in);
System.out.print("Enter a test score: ");
int grade1 = s.nextInt();
System.out.print("Enter a test score: ");
int grade2 = s.nextInt();
System.out.print("Enter a test score: ");
int grade3 = s.nextInt();
System.out.print("Enter a test score: ");
int grade4 = s.nextInt();
System.out.print("Enter a test score: ");
int grade5 = s.nextInt();
double avg = (grade1+grade2+grade3+grade4+grade5)/5.0;

if (avg >= 90.0) 
{
    System.out.println("Letter grade: A");
}
else if (avg >= 80.0) 
{
    System.out.println("Letter grade: B");
}
else if (avg >= 70.0) 
{
    System.out.println("Letter grade: C");
}
else if (avg >= 60.0) 
{
    System.out.println("Letter grade: D");
}
else 
{
    System.out.println("Letter grade: F");
}

Error checking

Conditional statements are very useful in handling error conditions in programs. You can check to see if the user’s input is what you expected before performing any calculations. For example, in the grade calculator we just wrote, we expect the test scores to be between 0 and 100. As an error condition, we could add this check after getting all the user input:

if (grade1<0 || grade1>100 || grade2<0 || grade2>100 || grade3<0 ||
    grade3>100 || grade4<0 || grade4>100 || grade5<0 || grade5>100) 
{
    System.out.println("Invalid input");
}
else 
{
    //put the average calculation and the code to print the letter grade here
}

Now, a letter grade will only be printed if all test scores had appropriate values.

Switch Statements

There is a second type of conditional statement in Java called a switch statement. These statements can be used as a shortcut over if statements when checking the value of variables or expressions.

Switch statement syntax

Here is the syntax of a switch statement:

switch (expression) 
{
    case val1:
        //first set of statements
        break;
    case val2:
        //second set of statements
        break;
    ...
    default:
        //last set of statements
}

Here, expression is either an expression or variable that has type char, int, or String (in more recent versions of Java). Inside the statement, val1, val2, etc. are possible values for expression. If expression equals val1, then we execute the statements inside the val1 case. If expression equals val2, then we execute the statements inside the val2 case. We can have as many cases as we want (as denoted by the …).

The default case is executed if expression does not evaluate to any of the case values. This default case is optional. The “break” statements at the end of each case mean that we will leave the switch statement at the end of a case. They are also optional, but if we leave them out then we will continue on to the statements in the next case (WITHOUT checking the case value). We will see an example of this in the next sections.

Switch statement example with ints

Here is an example that gets a month number (1-12) from the user and prints the corresponding month name:

Scanner s = new Scanner();
System.out.print("Enter month number (1-12): ");
int monthNum = s.nextInt();

String monthName;

switch(monthNum)
{
    case 1:
        monthName = "January";
        break;
    case 2:
        monthName = "February";
        break;
    case 3:
        monthName = "March";
        break;
    case 4:
        monthName = "April";
        break;
    case 5:
        monthName = "May";
        break;
    case 6:
        monthName = "June";
        break;
    case 7:
        monthName = "July";
        break;
    case 8:
        monthName = "August";
        break;
    case 9:
        monthName = "September";
        break;
    case 10:
        monthName = "October";
        break;
    case 11:
        monthName = "November";
        break;
    case 12:
        monthName = "December";
        break;
    default:
        monthName = "Invalid month";
        break;
}

System.out.println(monthName);

For example, if we ran our code fragment and entered 4 at the prompt, then the program would print “April”. If we ran it again and entered 13, then the program would print “Invalid month”.

Equivalent if…else if statement

We can always rewrite a switch statement using an if…else if statement that has an else if branch corresponding to each case in the switch. Here is our month name example repeated with an if…else if statement:

Scanner s = new Scanner();
System.out.print("Enter month number (1-12): ");
int monthNum = s.nextInt();

String monthName;

if (monthNum == 1)
{
    monthName = "January";
}
else if (monthNum == 2)
{
    monthName = "February";
}
else if (monthNum == 3)
{
    monthName = "March";
}
else if (monthNum == 4)
{
    monthName = "April";
}
else if (monthNum == 5)
{
    monthName = "May";
}
else if (monthNum == 6)
{
    monthName = "June";
}
else if (monthNum == 7)
{
    monthName = "July";
}
else if (monthNum == 8)
{
    monthName = "August";
}
else if (monthNum == 9)
{
    monthName = "September";
}
else if (monthNum == 10)
{
    monthName = "October";
}
else if (monthNum == 11)
{
    monthName = "November";
}
else if (monthNum == 12)
{
    monthName = "December";
}
else 
{
    monthName = "Invalid month";
}

System.out.println(monthName);

However, the structure of an if…else if statement can require more code that a switch statement (the expression we are evaluating must be retyped in each condition, and we often need to include brackets around each case), so switch statements are a convenient shortcut.

Switch statement example with chars

Here is an example that uses a switch statement to print out comments about a given letter grade:

Scanner s = new Scanner(System.in);
System.out.print("Enter your letter grade: ");

//this technique converts the string to a char 
//by getting the first character from the input string
char grade = (s.nextLine()).charAt(0);

switch (grade) 
{
    case 'A':
        System.out.println("Excellent");
        break;
    case 'B':
        System.out.println("Good");
        break;
    case 'C':
        System.out.println("Average");
        break;
    case 'D':
        System.out.println("Poor");
        break;
    case 'F':
        System.out.println("Failure");
        break;
    default:
        System.out.println("Invalid grade");
        break;
}

Depending on what grade the user entered, exactly one of the case statements will be printed.

Switch statement example without breaks

To see what happens when we leave some break statements out, suppose we want to repeat the letter grade example, but just print out whether the user passed (A, B, or C) or failed (D or F). Here’s what we would do:

switch (grade) 
{
    case 'A':
    case 'B':
    case 'C':
        System.out.println("Pass");
        break;
    case 'D':
    case 'F':
        System.out.println("Fail");
        break;
    default:
        System.out.println("Invalid grade");
        break;
}

If the user enters A, for example, then we will first go to case A in the switch statement. Since there is no break statement, we will go directly to case B (even though the grade entered doesn’t match that case). There is not a break statement in B either, so we will go to case C. There we will print “Pass” (which we should for an A grade) and break out of the switch statement.

Switch statement example with Strings

In more recent versions of Java, we can also use a switch statement to evaluate a String variable or expression. Here is an example that gets a month name from the user and prints out the corresponding month number:

Scanner s = new Scanner(System.in);
System.out.print("Enter a month name: ");

String monthName = s.nextLine();
int monthNum; 

switch (monthName) 
{
    case "January":
        monthNum = 1;
        break;
    case "February":
        monthNum = 2;
        break;
    case "March":
        monthNum = 3;
        break;
    case "April":
        monthNum = 4;
        break;
    case "May":
        monthNum = 5;
        break;
    case "June":
        monthNum = 6;
        break;
    case "July":
        monthNum = 7;
        break;
    case "August":
        monthNum = 8;
        break;
    case "September":
        monthNum = 9;
        break;
    case "October":
        monthNum = 10;
        break;
    case "November":
        monthNum = 11;
        break;
    case "December":
        monthNum = 12;
        break;
    default:
        monthNum = -1;
        break;
}

if (monthNum != -1)
{
    System.out.printf("Month number: %d%n", monthNum);
}
else
{
    //monthNum will be -1 if we went in our "default" switch case above
    System.out.println("Invalid month name");
}

The above example will only work correctly if the user types the month name using the format in our cases (capital first letter, lowercase subsequent letters). A trick to repeating this example WITHOUT checking for a specific format is to first convert the input month to lowercase, and then to change our cases to be in lowercase format:

Scanner s = new Scanner(System.in);
System.out.print("Enter a month name: ");

String monthName = s.nextLine();
int monthNum; 

switch (monthName.toLowerCase()) 
{
    case "january":
        monthNum = 1;
        break;
    case "february":
        monthNum = 2;
        break;
    case "march":
        monthNum = 3;
        break;
    case "april":
        monthNum = 4;
        break;
    case "may":
        monthNum = 5;
        break;
    case "june":
        monthNum = 6;
        break;
    case "july":
        monthNum = 7;
        break;
    case "august":
        monthNum = 8;
        break;
    case "september":
        monthNum = 9;
        break;
    case "october":
        monthNum = 10;
        break;
    case "november":
        monthNum = 11;
        break;
    case "december":
        monthNum = 12;
        break;
    default:
        monthNum = -1;
        break;
}

if (monthNum != -1)
{
    System.out.printf("Month number: %d%n", monthNum);
}
else
{
    //monthNum will be -1 if we went in our "default" switch case above
    System.out.println("Invalid month name");
}

Now, whether the user enters “September”, “september”, or “SePTembER”, the program will always print 9 as the month number.

Examples

This section includes three examples of full programs using conditional statements.

Example 1: max heart rate calculator

There are many different formulas for estimating a person’s maximum heart rate using their age and biological sex. Here is one such estimation:

For men: 220 – age
For women: 206 – 88% of age

(Every such formula is only an estimation, and may or may not be accurate for a particular person.) Below is a complete program that asks for a user’s age and sex, and then prints their maximum heart rate according to the estimation above.

import java.util.*;
public class Example1 
{
    public static void main(String[] args)
    {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter your age: ");

        int age = s.nextInt();
        System.out.print("Enter (m)ale or (f)emale: ");
        char mOrF = (s.nextLine()).charAt(0);

        if (mOrF == 'm' || mOrF == 'M') 
        {
            int max = 220-age;
            System.out.printf("Max HR: %d%n", max);
        }
        else if (mOrF == 'f' || mOrF == 'F') 
        {
            double maxF = 206  0.88*age;
            System.out.printf("Max HR: %.2f%n" + maxF);
        }
        else 
        {
            System.out.println("Invalid input");
        }
    }
}

Example 2: minimum of two numbers

In this example, we will get two numbers as input from the user, and we will print out whichever number is smaller. In the case of a tie, it doesn’t matter which number we print.

import java.util.*;
public class Example2 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int num1 = s.nextInt();

        System.out.print("Enter the second number: ");
        int num2 = s.nextInt();

        if (num1 < num2) 
        {
            System.out.println(num1);
        }
        else
        {
            System.out.println(num2);
        }
    }
}

Example 3: temperature converter

In this example, we will ask the user for a temperature and the system being used (Fahrenheit or Celsius). We will then print the equivalent temperature in the other system (i.e., if we start with Fahrenheit then we will convert to Celsius, and vice versa). Here are the formulas that are used to convert between the two (C is Celsius and F is Fahrenheit):

C = (5/9)*(F-32)
F = (9/5)*C+32

Here is our full program:

import java.util.*;
public class Example3 
{
    public static void main(String[] args) 
    {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the temperature: ");

        double temp = s.nextDouble();
        System.out.print("Enter (f)ahrenheit or (c)elsius: ");

        char system = (s.nextLine()).charAt(0);
        double newTemp;

        if (system == 'f' || system == 'F') 
        {
            newTemp = (5.0/9.0)*(temp-32);
        }
        //we are assuming that the user typed either f or c
        else 
        {
            newTemp = (9.0/5.0)*temp + 32;
        }

        System.out.printf("Converted: %.2f%n", newTemp);
    }
}