Object Oriented Programming: Topic 2 Additional Material

The switch statement

In this topic we will examine the switch statement. We will also look at prefix and postfix operators in more detail.

The switch statement

Java, in common with most C-based languages, includes an alternative conditional statement to the if statement, namely the switch statement. Often we find ourselves having to write very long winded if/else statements to cover a wide range of possibilities, e.g:

public class IfCallingCodesApp
{
    public static void main (String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the international dialling code :");
        String codeAsString = scanner.nextLine();
        int code = Integer.parseInt(codeAsString);
        
    
        
        if(code == 44)
        {
            System.out.println("UK");
        }
        else if (code == 33)
        {
            System.out.println("France");
        }
        else if (code == 1)
        {
            System.out.println("USA or Canada");
        }
        else if (code == 49)
        {
            System.out.println("Germany");
        }
        else
        {
            System.out.println("Don't know");
        }
    }
}
This works, but arguably the code is a bit long-winded and hard to read. An alternative is to use the switch statement, shown below:
public class SwitchCallingCodesApp
{
    public static void main (String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the international dialling code :");
        String codeAsString = scanner.nextLine();
        int code = Integer.parseInt(codeAsString);
        
    
        switch(code)
        {
            case 44:
                System.out.println("UK");
                break;
                
            case 33:
                System.out.println("France");
                break;    
                
            case 1:
                System.out.println("USA or Canada");
                break;
                
            case 49:
                System.out.println("Germany");
                break;
                
            default:
                System.out.println("Don't know");
                
        }
    }
}
This shows the use of a switch statement. We switch on the variable we want to test (code here) and consider the case of each of the values we want to test for. In each case statement we write all the code relating to that case (e.g. 44 for UK) and then break out of the switch statement. Note that the break is compulsory in this example. If we miss the break out, it will continue running the next case. (Why is this? The next example, below, will explain).

Also note the default case. This will trap anything not covered by the specified cases. So if the user enters something other than 44, 33, 1 or 49, then "Don't know" will be printed.

Exercise 1

Try the switch example above. Remove the break statements from each case and try running it again, testing out each recognised dialling code. What happens?

Multiple cases, one effect

There are many cases where we want a group of cases to have the same effect. For example imagine a program which displays which season a month is in. This might look like this:

public class SeasonsSwitchApp
{
    public static void main (String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the month :");
        String month = scanner.nextLine();
    
        
    
        switch(month)
        {
            case "December":
            case "January":
            case "February":
                System.out.println("Winter");
                break;
                
            case "March":
            case "April":
            case "May":
                System.out.println("Spring");
                break;    
                
            case "June":
            case "July":
            case "August":
                System.out.println("Summer");
                break;
                
            case "September":
            case "October":
            case "November":
                System.out.println("Autumn");
                break;
                
            default:
                System.out.println("Not a real month");
                
        }
    }
}
In this example, note how we group cases together. So if month is either December, January or February, Winter will be printed. This is why cases "fall through" to the next case if the break is missing. This example also shows that you can use strings in switch statements, as well as integers. This has not always been the case, but has been since Java 7.

Exercise 2

  1. Using a switch statement, write a program which reads in a grade (A, B, C, D or F) and displays the equivalent degree classification. Use the following guidelines:
  2. Using a switch statement, write a program which reads in two numbers and an operator (+, -, / or *) and performs the appropriate mathematical calculation.

Prefix and postfix operators

You have already seen statements such as:

a++;
to increase a variable by one. This is called a postfix operator because the "++" comes after the variable. However, we can also have the related prefix operator:
++a;
which does the same thing. What, then, is the difference between them? They have different meanings when the variable is assigned to another. For example we can have statements such as:
int b = a++;
or
int c = ++a;
What do these two statements do and what is the difference between them?

This can have consequences for loops. For instance:

while(++i < 10)
{
    System.out.println(i);
}
will count from 1 to 9, but
while(i++ < 10)
{
    System.out.println(i);
}
will count from 1 to 10.

This is because the statement:

while(++i < 10)
increases i first and then compares it with the value 10. So if i is 9, i will be increased by one first and then compared to 10. Since it will now be 10, the loop will not run.

By contrast:

while(i++ < 10)
compares i with the value 10 first and then increases it by one. So if i is 9, i will be compared with 10; it will be less than 10 so the loop will run. After comparing i with 10, i will be increased by one - but by that time the test will already have been passed. So the result will be that the loop will run another time with i having the value 10.