为什么 java switch 语句不能处理 null,因为它有一个“默认"条款?

编程入门 行业动态 更新时间:2024-10-09 15:20:19
本文介绍了为什么 java switch 语句不能处理 null,因为它有一个“默认"条款?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

为什么java switch 语句不能处理null,因为它有一个default"子句?

Why java switch statement can't handle null, since it has a "default" clause?

例如,如果你有类似的东西

For example, if you have something like

switch(value){ case VAL1: do_something1(); break; case VAL2: do_something2(); break; default: do_something3(); }

default"不应该处理任何其他值,例如 null?

shouldn't "default" deal with any other value, such as null?

推荐答案

一如既往,它在 JLS 中:

以下所有条件都必须为真,否则会发生编译时错误:

  • ...
  • 没有开关标签是null.

...禁止使用 null 作为开关标签可以防止编写永远无法执行的代码.如果 switch 表达式是引用类型,即 String 或装箱的原始类型或枚举类型,那么如果表达式的计算结果为 null 在运行时.在 Java 编程语言的设计者的判断中,这比默默地跳过整个 switch 语句或选择执行 default 之后的语句(如果有)更好的结果> 标签(如果有的话).

... The prohibition against using null as a switch label prevents one from writing code that can never be executed. If the switch expression is of a reference type, that is, String or a boxed primitive type or an enum type, then a run-time error will occur if the expression evaluates to null at run time. In the judgment of the designers of the Java programming language, this is a better outcome than silently skipping the entire switch statement or choosing to execute the statements (if any) after the default label (if any).

更多推荐

为什么 java switch 语句不能处理 null,因为它有一个“默认"条款?

本文发布于:2023-07-21 07:23:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1175412.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:因为它   语句   有一个   条款   switch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!