Switch statement in Java

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..println("#000000");
break;
case "white":
System..println("#FFFFFF");
break;
case "silver":
System..println("#C0C0C0");
break;
default:
System..println("default color");
System..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..println("#000000");
break;
case "white":
System..println("#FFFFFF");
case "silver":
System..println("#C0C0C0");
default:
System..println("default color");
System..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 coditions. For example

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

switch(str) {
case "apple":
case "orange":
case "banana":
System..println("Fruit");
break;
case "cucumber":
case "tomato":
case "broccoli":
System.out.println("Vegetable");
break;
default:
System..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..println("One");
break;
case 2:
System..println("Two");
break;
case 3:
System..println("Three");
break;
default:
System..println("Some number");
}
}
}

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

Software Developer, Java Instructor https://www.techleadacademy.io/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store