Switch Case Java

Aap Ki Apni School
2 min readFeb 3, 2021

Hello Guys,

Today we will discuss Switch Case java. We will discuss some key points those are important for Switch case. We will see what is default case and is it needed? We will discuss nested switch case and break keyword. We will check Java Wrapper in Switch Statement,Can we use float in switch case in Java? and Is switch case faster than if else Java? point.

Switch case java:

Switch case is like if-else-if statement. Switch case java execute one statement from multiple conditions.We can give expression of these type byte, short, int, long, enum types, String and some wrapper class like Integer,Byte,Long,Short. From Java 7 it accept String also.

Key Points:

  • Case value must be unique otherwise java compiler throw error.
  • The case value must be literal or constant. It doesn’t allow variables.
  • Switch case type must be byte, short, int, long, enum types, String and some wrapper class like Integer,Byte,Long,Short types.
  • Switch case can have default case that is used if no case found.It is optional.
  • After each case we can put break keyword but it is optional.

Syntax:

switch(expression){ 
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
case value3:
break;
......
default:
code to be executed if all cases are not matched;
}

Sample Code Without Break Keyword: Java Switch case execute all the statement after first match if break keyword not available.

package youtubeClass;

public class Test {

public static void main(String[] args) {

String color=”red”;

switch(color)

{

case “red”:System.out.println(“This is Red color.”);

case “green”:System.out.println(“This is Green color.”);

case “blue”:System.out.println(“This is Blue color.”);

default:System.out.println(“This is default color.”);

}

}

}

OutPut:

This is Red color.

This is Green color.

This is Blue color.

This is default color.

Sample Code With Break Keyword:It execute that particular case if break keyword is available.

package youtubeClass;

public class Test {

public static void main(String[] args) {

String color=”red”;

switch(color)

{

case “red”:System.out.println(“This is Red color.”);

break;

case “green”:System.out.println(“This is Green color.”);

break;

case “blue”:System.out.println(“This is Blue color.”);

break;

default:System.out.println(“This is default color.”);

}

}

}

Output:

This is Red color.

This article is originally written in

More details

--

--

Aap Ki Apni School

I am a software developer. I have been working in IT since 5 years. I am interested in learning new things.