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
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.