New Java 7 Feature: String in Switch support

New Java 7 Feature: String in Switch support

One of the new features added in Java 7 is the capability to switch on a String.

With Java 6, or less

  1. String color = "red";  
  2.   
  3. if (color.equals("red")) {  
  4.   System.out.println("Color is Red");  
  5. else if (color.equals("green")) {  
  6.   System.out.println("Color is Green");  
  7. else {  
  8.   System.out.println("Color not found");  
  9. }  

With Java 7:

  1. String color = "red";  
  2.   
  3. switch (color) {  
  4. case "red":  
  5.   System.out.println("Color is Red");  
  6.   break;  
  7. case "green":  
  8.   System.out.println("Color is Green");  
  9.   break;  
  10. default:  
  11.   System.out.println("Color not found");  
  12. }  

Conclusion

The switch statement when used with a String uses the equals() method to compare the given expression to each value in the case statement and is therefore case-sensitive and will throw a NullPointerException if the expression is null. It is a small but useful feature which not only helps us write more readable code but the compiler will likely generate more efficient bytecode as compared to the if-then-else statement.

ShareThis

Related posts:

  1. Java 7: New Feature – automatically close Files and resources in try-catch-finally
  2. 2 ways to convert Java Map to String
  3. 3 ways to serialize Java Enums
  4. How to trim() No-Break space ( ) when parsing HTML
  5. Installing Java 7 on Mac OS X

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值