Switch Case Example In Java

Hello everyone!! We 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 Switch_Case {

public static void main(String[] args) {
 
int adult_Age;

adult_Age = 18;
 
if(adult_Age == 16)
{
System.out.println("statements go here for adult age 16.....");
}
if(adult_Age == 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 adult_Age and the adult age is 18.

All you have to do right now is to make an if statement for each adult age, if adult_Age 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.

And after 16, if adult_Age 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 adult_Age 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

Also Read – Best Way To Remove Single Character From String

public class Switch_Case {

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

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *