Java —— 基础笔记:条件判断优化

xiaoxiao2021-02-28  92

今天才知道条件判断语句还可以这么写。

当多个条件判断中包含判断变量是否为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放最前面),感觉好多了。

转载请注明原文地址: https://www.6miu.com/read-46766.html

最新回复(0)