Decision Structures

All programming languages allow you to perform certain actions based on decisions that need to be made. In Java we use If and Switchstatements to check conditions and decide what to do.

If Statements

If we want to check whether a particular number is an even number (divisible by 2 without remainder) we could do so as follows:

if (number % 2 == 0)
   System.out.println("The number " + number + " is even.");
   System.out.println("The number " + number + " is even.");

Switch Statements

A switch statement allows us to perform an action based on an integer number. We have a number of “cases” and the case that is execute is decided by the integer value given to the switch statement.


If we would like to print out a month name if given a number we could use a switch statement as follows:

The switch compares the number provided in the brackets with each case number until it finds a match. If it does not find a match goes to the “default” case.

Here the integer variable month contains the value 8 so the switch statement will execute case 8 and print out “August”.

int month = 8;
switch (month)
   case 1: System.out.println("January"); break;
   case 2: System.out.println("February"); break;
   case 3: System.out.println("March"); break;
   case 4: System.out.println("April"); break;
   case 5: System.out.println("May"); break;
   case 6: System.out.println("June"); break;
   case 7: System.out.println("July"); break;
   case 8: System.out.println("August"); break;
   case 9: System.out.println("September"); break;
   case 10: System.out.println("October"); break;
   case 11: System.out.println("November"); break;
   case 12: System.out.println("December"); break;
   default: System.out.println("Not a month!");break;

The last case option, default, is used only if the integer provided to the switch statement does match match any othe case.