java 判断字符串是否为空

四种判断为空表示方式:

1、str == null;
2、"".equals(str);
3、str.length() == 0;
4、str.isEmpty();
  • 1
  • 2
  • 3
  • 4

代码中的四种不为空的运用:

if(str != null && !"".equals(str));//效率相对较低
if(str != null && str.length() > 0); //推荐使用,效率高
if(str != null && !str.isEmpty());//java se 6.0 后出现,出于兼容性的考虑,最好不用
if(str != null && str != "");//效率和二、三差不多(个人不太推荐,前几天写一个业务进行判断后,调试发现str = "",但是还是进入了判断函数,后面换成了方法二,具体原因一直没搞明白)

//后面三种效率都差不多,但综合考虑,根据长度判断字符串是否为空比较好
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

代码中的四种为空的运用:

if(str == null || "".equals(str)); 
if(str == null || str.length() <= 0);
if(str == null || str.isEmpty());
if(str == null || str == ""); //字符串比较不推荐用‘==’
  • 1
  • 2
  • 3
  • 4

str == null要放在判断前面的原因:

  1. null 是一个对象的值,非字符串,String str = null,表示声明一个字符串对象的引用,指向为null,此时没有指向任何内存空间。
  2. ""是一个为空的字符串,长度为0,String str = “”,表示声明一个字符串类型的引用,指向的是空字符串的内存空间。
  3. 如果str = null,但是没有放到判断前面,此时操作str.length()和.equals()就会抛出java.lang.NullPointerException异常

String s = null;

   1. if((s!=null)&(s.length()>0)){}

   2. if((s!=null)&&(s.length()>0)){}

   3. if((s==null)|(s.length()==0)){}

   4. if((s==null)||(s.length()==0)){}

上述案例在java运行情况中,1,3均抛出NullPointerException异常。

 

if(currentPage == null ||currentPage.length()== 0 || "".equals(currentPage)){
    currentPage = "1";
}

if (rows == null || rows.length() == 0 || "".equals(rows)){
    rows = "5";
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值