int numLetters = 0; Day day = Day.WEDNESDAY; int result = switch (day) { case MONDAY, FRIDAY, SUNDAY -> numLetters = 6; case TUESDAY -> numLetters = 7; case THURSDAY, SATURDAY -> numLetters = 8; case WEDNESDAY -> numLetters = 9; default -> throw...
在Java 17中,引入了switch表达式(Switch Expressions)、yield关键字与->符号。 可以在标签case(label case)中使用yield关键字返回一个值。 示例代码如下所示: publicclassSwitchMain{publicstaticvoidmain(String[] args){Stringday="Monday";Stringr=switch(day) {// switch表达式case"Monday","Tuesday","Wednesday...
在这个表达式中使用 switch 返回时不需要break关键字,但需要default case。 代码语言:javascript 代码运行次数:0 运行 AI代码解释 privatestaticvoidimprovedSwitch(Fruit fruit){String text=switch(fruit){caseAPPLE,PEAR->{System.out.println("the given fruit was: "+fruit);yield"Common fruit";}caseORANGE,AVOC...
Pattern matching for switch is introduced as apreview feature. As the name suggests, it adds patterns to the case labels in the switch statementsandswitch expressions. The type of theselector expressionthat can be used with a switch is expanded to any reference value. Also, case labels are n...
In addition, it should be noted that for the function of pattern matching in switch expressions, the implementation in JDK 17 is still the preview version, so understanding is the main thing. It is not recommended for use in the official environment at present, and the possibility of further...
For example: switch ( expression ) { cases } See Java Language Specification: 15.29 Switch Expressions Since: 12 Nested Class Summary Nested classes/interfaces declared in interface com.sun.source.tree.Tree Tree.Kind Method Summary All MethodsInstance MethodsAbstract Methods Modifier and Type Method ...
从switch语句说起 要注意区分下,switch statement(switch语句)与switch expressions(switch表达式)两个词的不同。switch语句是大家熟悉的旧的switch用法,而 switch表达式则是我们今天要说的。 其实,从这两者之间的名字来看,就能猜到两者肯定有很大的相似性,也一定会有不同。
Bierman:Completeness appeared withswitchexpressions that were finalized in Java 14. When you are evaluating any expression in Java, you expect it to result in either avalueor anexception. When we introducedswitchexpressions, we had a question in the design process: What if your cases don’t cov...
SeeJDK 17 Release Notesfor detailed information about this release. The following are some of the important additions and updates in Java SE 17 and JDK 17: New Language Features The preview feature Pattern Matching forswitchExpressions and Statements is introduced in this release. This feature allow...
该特性先后由JDK12的JEP 325: Switch Expressions (Preview)、JDK13的JEP 354: Switch Expressions (Preview)引入,并在JDK14的JEP 361: Switch Expressions正式转正。 为switch提供模式匹配功能,允许switch对一个表达式进行多个模式的匹配,每个模式都有一个特定的操作,这样就可以简洁而安全地表达复杂的面向数据的查询...