How to check null on StringBuilder?

前端 未结 6 2226
自闭症患者
自闭症患者 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

    In Java, null is a reference literal. If a variable is null then is not referring to anything.

    So, if you have StringBuilder s = null, that means that s is of type StringBuilder but it is not referring to a StringBuilder instance.

    If you have a non-null reference then you are free to call methods on the referred object. In the StringBuilder class, one such method is length(). In fact if you were to call length() using a null reference then the Java runtime will throw a NullPointerException.

    Hence, this code is quite common:

    If (s == null || s.length() == 0/*empty if the length is zero*/){
        // do something
    

    It relies on the fact that evaluation of || is from left to right and stops once it reaches the first true condition.

提交回复
热议问题