How to check null on StringBuilder?

前端 未结 6 2205
自闭症患者
自闭症患者 2021-02-18 18:39

I want to check for null or empty specifically in my code. Does empty and null are same for StringBuilder in Java?

For example:

StringBuilde         


        
6条回答
  •  爱一瞬间的悲伤
    2021-02-18 19:15

    Null mean, there are no object in the heap for that reference variable. This is common to all java object, not specific to StringBuilder and Empty means, "".

    In your code, you have created a StringBuilder object, so checking null is redundant. And, You can check empty by using isEmpty() method in from java String api

    if(state.tostring().isEmpty()) {
    //
    }
    

    And checking null is correct. Find the corrected version here

    if (state == null) {
    // ...bla 1
    } else if (state.tostring().isEmpty()) {
    //... bla 2
    }
    

    Your second if condition will throw NullPointerException, if the state is null. So if should be nested with if else

提交回复
热议问题