Java: Switch

What is Switch?

Switch is almost like a for loop. Like a for loop, you have to define a variable. The only difference is that it needs to be defined normally, in the main function.

package com.lessons;

public class Switch {
     public static void main(String[] args) {
          int movieRating = 4;

//The variable movieRating = 4;

          switch (movieRating){

               case 1: System.out.println(“That was a terrible movie.”);

// If movieRating = 1, execute case 1 only
               case 2: System.out.println(“That was an OK movie.”);

// If movieRating = 2, execute case 2 only
               case 3: System.out.println(“That was a good movie.”);

// If movieRating = 3, execute case 3 only
               case 4: System.out.println(“That was a great movie.”);

 // If movieRating = 4, execute case 4 only
               case 5: System.out.println(“That was an excellent movie.”);

// If movieRating = 5, execute case 5 only
               default: System.out.println(“I haven’t seen that movie.”);

// If movieRating does not equal 1,2,3,4, or 5, execute the default


How it Works

The First Step to making a switch statement is to define a variable. In this case, the variable defined was movieRating.

The Second Step is to make the switch function. In the example above, it says switch(movieRating). This means that the switch statement will be based on the variable movieRating. If movieRating = 1, case 1 gets executed. If movieRating = 2, case 2 gets executed. If movieRating = 3, case three gets executed. If movieRating does not equal any of the cases the default line will get executed, and “I have not seen that movie” will get printed on the screen.

After every case there is the word Break. Without the break, Java will check if movieRating matches any of the cases after the matching one. With the break, “That was a great movie” will get printed on the screen. Without the break, the code below will get printed on the screen.

That was a great movie.

That was an excellent movie.

I haven’t seen that movie.

Leave a comment