top of page
Search

Java Switch Case

Ever needed to write a million if-else statements to the point where your brain is breaking and you're about an inch away from throwing your computer against a wall? Well, before you go so far as to break your computer, try a Switch Case!


Switch cases are an easy way to create conditional logic in a code, especially when a variable has many potential variables. The "switch" will first consider a variable:

int n;
   switch(n){
   

Then, depending on the value of 'n', the program can execute a conditional body of code. You must include the "break" command in order exit the switch case, other all subsequent lines may execute.

      case 1:      //equivalent to the logic if(n == 1) 
        System.out.println("n is less than 2");
        break;

      case 3:
        System.out.println("n is less than 5");
        break;

      case 5:
        System.out.println("n is 5");
        break;

Finally, include the default statement. This serves as a catch-all (like an else statement).

      default:
        System.out.println("I don't know what n is");

    }

And that's it!


See you next time!

Bronwyn

 
 
 

Recent Posts

See All

Comments


bottom of page