Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use a switch statement in Java

I appreciate that anything that can be done by a switch statment, can be done by an if else statement.

But are there stylistic rules for when one should use the switch rather than if else statment.

like image 933
Dan Avatar asked Jan 20 '10 16:01

Dan


People also ask

When should you use a switch statement?

Switch statements are cleaner syntax over a complex or stacked series of if else statements. Use switch instead of if when: You are comparing multiple possible conditions of an expression and the expression itself is non-trivial. You have multiple values that may require the same code.

Which data type is ideal for using with a switch statement?

The expression used in a switch statement must have an integral or enumerated type, or be of a class type in which the class has a single conversion function to an integral or enumerated type.

When should you use switch statement over if statement and vice versa?

Use switch every time you have more than 2 conditions on a single variable, take weekdays for example, if you have a different action for every weekday you should use a switch. Other situations (multiple variables or complex if clauses you should Ifs, but there isn't a rule on where to use each.

What is advantage of switch in Java?

The switch statement has a fixed depth. It allows the best-optimized implementation for faster code execution than the “if-else if” statement. It is easy to debug and maintain the programs using switch statements. The switch statement has faster execution power.


1 Answers

Well, switch feels "lighter" in many cases than an if/else if ladder, in my opinion. Basically you don't have that much syntax with braces and parentheses in the way of your code. That being said, switch inherits C's syntax. That means you have break and only a single scope for variables unless you introduce new blocks.

Still, the compiler is able to optimize switch statements into a lookup table and perform compile-time checking for literals when dealing with enumerations. So, I'd suggest that it's usually preferable to use switch over if/else if if you're dealing with numeric or enum types.

like image 126
Joey Avatar answered Oct 17 '22 07:10

Joey