首页 > 编程语言 > 详细

java7 语法糖 之 switch 声明string

时间:2015-10-17 12:09:25      阅读:249      评论: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

版权声明:本文博主原创文章,博客,未经同意不得转载[http://blog.csdn.net/doctor_who2004]。

java7 语法糖 之 switch 声明string

原文:http://www.cnblogs.com/mengfanrong/p/4887218.html

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