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.

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.

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

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

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.

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

--

--

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