首页 > 编程语言 > 详细

java7 语法糖 之 switch 语句中的string

时间:2014-10-29 21:35:29      阅读:316      评论:0      收藏:0      [点我收藏+]

  Jdk7新增的switch 语句中常量可以string类型,

例如:

@Test
	public void test_1(){
		String string = "hello";
		switch (string) {
		case "hello":
			System.out.println(string);
			break;

		default:
			throw new IllegalArgumentException("非法参数");
		}
	}

  语法糖的背后,其实用的对待string 类型时候,用的是hashCode() 方法转换的.

所以string 类型不能为 NULL.

例如:

@Test
	public void test_3(){
		String string = null;
		expectedException.expect(NullPointerException.class);
		switch (string) {
		case "hello":
			System.out.println(string);
			break;

		default:
			throw new IllegalArgumentException("非法参数");
		}
	}

会抛出异常
NullPointerException

java7 语法糖 之 switch 语句中的string

原文:http://blog.csdn.net/doctor_who2004/article/details/40592633

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!