Java —— 基础笔记:条件判断优化
今天才知道条件判断语句还可以这么写。
当多个条件判断中包含判断变量是否为null时,普通写法:
String str = null;
if(str != null){
if(str.length()>10){
System.out.println("满足条件");
}else{
System.out.println("不满足");
}
}else{
System.out.println("不满足");
}
其实,对于与(&&)判断,多个条件应该是顺序判断的,当判断某个条件不满足时,结果直接为false,不会再往下判断。上面可优化为:
if(str !=null && str.length() > 10){
System.out.println("满足条件");
}else{
System.out.println("不满足");
}
这样不会出现空指针异常(注意判断是否为null放最前面),感觉好多了。
还没有评论,来说两句吧...