何时在Java中使用switch语句 [英] When to use a switch statement in Java

查看:133
本文介绍了何时在Java中使用switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很欣赏任何可以通过switch语句完成的事情都可以通过if else语句来完成。

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

但是有什么样的规则应该使用开关而不是if else语句。

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

推荐答案

那么,开关感觉在很多情况下,打火机比如果 / ,否则如果梯,我认为。基本上,您的代码方式中没有大括号和括号的语法。话虽这么说, switch 继承了C的语法。这意味着你有 break 并且只有一个变量范围,除非你引入新的块。

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.

仍然是编译器能够在查询表中优化 switch 语句,并在处理枚举时对文字执行编译时检查。所以,我建议通常最好使用切换而不是 if / else if 如果您正在处理数字或枚举类型。

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.

这篇关于何时在Java中使用switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆