I want to check for null or empty specifically in my code. Does empty and null are same for StringBuilder
in Java?
For example:
StringBuilder state = new StringBuilder();
StringBuilder err= new StringBuilder();
success = executeCommand(cmd, state, err);
/* here executeCommand() returns empty or null in state, I cant make changes in <br/> executeCommand() so can I check it in my code somehow for state, if its null or empty? */<br/>
if (state == null) { //do blabla1 }
if (state.tostring().equals("")) { //do blabla2 }
Does above code make sense or how should I change it?
You can use the Length property: Gets or sets the length of the current StringBuilder object. It would have been easy to put public bool Empty { get; } = this. Length == 0; .
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.
so you can use the fact that StringBuffer. length() returns zero (or not) to check if the buffer is empty (or not).
append. Appends the specified string to this character sequence. The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null , then the four characters "null" are appended.
No, null
and empty
are different for StringBuilder
.
StringBuilder nullBuilder = null;
if(nullBuilder == null) {
System.out.println("Builder is null");
}
&
StringBuilder emptyBuilder = new StringBuilder("");
if(emptyBuilder == null || emptyBuilder.toString().equals("")) {
System.out.println("Builder is empty");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With