Java Tutorial #14 — Case logic / structure / breaking.


Topics Discussed: Case logic, case structure, case scope, breaking, case fallthrough, case study calculator

Source Code Available Here


Case Logic
Case logic is tremendously useful in cases where you might have something like a menu where a user selects something from a set of options. The basic syntax of a case is as follows:


int x = input.nextInt();
switch (x){  //x could be anything, int, double, char, etc.
     case 0:{  //this will execute if x = 0
     //do stuff
     break;
     }//end case 0

     case 1:{  //this will execute if x = 1
     //do stuff
     break;
     }//end case 1

     case 2:{  //this will execute if x = 2
     //do stuff
     break;
     }//end case 2

     case 3:{ //this will execute if x = 3
     //do stuff
     break;
     }//end case 3

     default:{ //this will happen if none of the other cases are true
     //do stuff
     }//end default
}  //End switch

Cases don’t offer much in terms of functionality that you couldn’t have accomplished with just if / else statements. The primary advantage that you have with cases is structure and readability. You can look at a case and immediately tell what it is doing, whereas a complex if might take a lot more time / effort to comprehend.