Switch Statement in Java in Under 5 mins

Rana M. Suleman
1 min readApr 12, 2021

Syntax

switch(expression) {
case a:
// code block
break;
case b:
// code block
break;
default:
// code block
}

Explanation

The switch statement allows a value to be checked against a number of values.

Here we can take an example of an Employee whose status needs to be verified against these values i.e Permanent, Intern and Contractual, etc

String status = Employee.status; // Employee status is : Internswitch(status) {
case "Permanent":
// Allow all benefits
break;
case "Intern":
// Allow limited benefits
break;
case "Contractual":
// Allow contractual benefits
break;
default:
// Provide basic Salary
}

As in the above example, the status of the employee is being matched with the cases in order as they appear. When matched, the statement inside the matched case will be executed following a break statement exiting the switch statement.

If there isn’t any break statement the flow will continue towards the other cases and will stop after finally reaching the default block & executing the statement inside it.

Key points to remember

  • The datatype it supports are short, byte, int, long, char, and their wrappers alongside with String and enums.
  • The case value data type must be of what is passed inside the switch also the values of the cases must be unique.
  • Default block is optional in the Switch statement

For more go to buffernest.com

--

--

Rana M. Suleman

Business oriented technology enthusiast, sharing ideas from the idea valley inside my immensely curious mind, A boring Software developer and a Gaming Nerd