Switch Case Example In Java

Hello everyone!! Welcome to flower brackets blog. In this post we are going to delve into switch case example in java.

What a switch statement does is, it tests one variable and depending on the output it gives you multiple choices.

Before we learn switch statement let me show you what we had to do with conventional way(using if statement),

Example:

public class SwitchCase
{
   public static void main(String[] args)
   {
      int adultAge;

      adultAge = 18;
 
      if(adultAge == 16)
      {
         System.out.println("statements go here for adult age 16.....");
      }
      if(adultAge == 17)
      {
         System.out.println("statements go here for adult age 17....");
      }
      ............... so on
   }
}

As you can see, above example tells you adult age. So, we have a variable called adultAge and the adult age is 18.

All you have to do right now is to make an if statement for each adult age, if adultAge is equal to 16 and then we would have to put something like “system” then you put “out” stuff like that and it will just pains in writing code.

Also Read – Best Way To Remove Single Character From String

And after 16, if adultAge is equal to 17 and then do your stuff down. Here, as you can see we do not have to type all that stuff for each number.

Any programmer would wish there was an easiest way to test adultAge for a bunch of different things.

Well actually we do not have to write ‘n’ number of if statements rather only write something called a switch statement once and it will give you many different options so instead of writing ‘n’ number of if statements let me show you guys an example on switch case statement in java,

Example: Switch Case Example In Java

public class SwitchCase
{
   public static void main(String[] args)
   {
      for(int a = 0; a <= 3; a++)
      {
         switch(a)
         {
            case 0:
            System.out.println("a is 0");
            break;
 
            case 1:
            System.out.println("a is 1");
            break;
 
            case 2:
            System.out.println("a is 2");
            break;
 
            default:
            System.out.println("a is greater than 2");
         }
      }
   }
}

Output:

Switch Case Example In Java

You May Also Like