java7新特性之—String values in a switch statement

Java7引入了一项新特性,允许在switch语句中使用String类型,这一变化简化了代码并提高了效率。例如,可以使用字符串字面量进行匹配,而不仅仅是整数或者枚举类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java7新特性之—String values in a switch statement

Strings in switch


The Java switch statement allows you to write an efficient multiple-branch statement
without lots and lots of ugly nested ifs—like this:


public void printDay(int dayOfWeek) {
switch (dayOfWeek) {
case 0: System.out.println("Sunday"); break;
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
case 4: System.out.println("Thursday"); break;
case 5: System.out.println("Friday"); break;
case 6: System.out.println("Saturday"); break;
default: System.err.println("Error!"); break;
}
}

In Java 6 and before, the values for the cases could only be constants of type byte,
char, short, int (or, technically, their reference-type equivalents Byte, Character,
Short, Integer) or enum constants. With Java 7, the spec has been extended to allow
for the String type to be used as well. They’re constants after all.

public void printDay(String dayOfWeek) {
switch (dayOfWeek) {
case "Sunday": System.out.println("Dimanche"); break;
case "Monday": System.out.println("Lundi"); break;
case "Tuesday": System.out.println("Mardi"); break;
case "Wednesday": System.out.println("Mercredi"); break;
case "Thursday": System.out.println("Jeudi"); break;
case "Friday": System.out.println("Vendredi"); break;
case "Saturday": System.out.println("Samedi"); break;
default: System.out.println("Error: '"+ dayOfWeek
➥ +"' is not a day of the week"); break;
}
}

In all other respects, theswitch statement remains the same. Like many Project Coin
enhancements, this is really a very simple change to make life in Java 7 a little bit easier.

该新特性只是java的语法糖。

Syntactic sugar
A phrase that’s sometimes used to describe a language feature is “syntactic sugar.”
This means that the syntax form is redundant—it already exists in the language—but
the syntactic sugar form is provided because it’s easier for humans to work with.
As a rule of thumb, a feature referred to as syntactic sugar is removed from the compiler’s representation of the program early on in the compilation process—it’s said
to have been “desugared” into the basic representation of the same feature.
This makes syntactic sugar changes to a language easier to implement because they
usually involve a relatively small amount of work, and only involve changes to the
compiler (javac in the case of Java).


读书笔记:The Well-Grounded Java Developer
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Dreamer who

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值