Switch Statement in Java

Beknazar
3 min readMar 25, 2021

--

If provided value to our switch will match with the value of one of the cases then this case will be executed.

public class Main {
public static void main(String[] args) {
String str = "white";

switch(str) {
case "black":
System.out.println("#000000");
break;
case "white":
System.out.println("#FFFFFF");
break;
case "silver":
System.out.println("#C0C0C0");
break;
default:
System.out.println("default color");
System.out.println("#000000");
}
}
}

The above program will print #FFFFFF because the value of String str is white and the second case has value white so they are matching and this case will get executed. The switch statement cannot have two cases with similar values, it will not just compile.

public class Main {
public static void main(String[] args) {
String str = "white";

switch(str) {
case "black":
System.out.println("#000000");
break;
case "white":
System.out.println("#FFFFFF");
case "silver":
System.out.println("#C0C0C0");
default:
System.out.println("default color");
System.out.println("#000000");
}
}
}

Exact same code but without the last two break keywords. The program will print

#FFFFFF
#C0C0C0
default color
#000000

break keyword stops the case execution. Without break, it will jump to the next case and so on. So it’s important to have it. Sometimes we can avoid breaks to meet multiple conditions. For example

public class Main {
public static void main(String[] args) {
String str = "apple";

switch(str) {
case "apple":
case "orange":
case "banana":
System.out.println("Fruit");
break;
case "cucumber":
case "tomato":
case "broccoli":
System.out.println("Vegetable");
break;
default:
System.out.println("I don't know");
}
}
}

Output from the above program is Fruit because the first case is a match and it will be executed. It’s an empty case and there is no break so it will go to the next case and there is no break as well and it will go to the next one. Here it will print out and there is a break so it will exit the switch statement.

The switch statement can work with specific data types only.

  • byte and Byte
  • short and Short
  • char and Character
  • int and Integer
  • String
  • enum values

The last thing I want to discuss is the default statement. Default statement executed when there is no match with cases. It’s optional and can appear anywhere within the switch statement.

public class Main {
public static void main(String[] args) {
int num = 7;

switch(num) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Some number");
}
}
}

Output is Some number because there is no case with value 7 so the default case is executed.

--

--

Beknazar
Beknazar

No responses yet