Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check null on StringBuilder?

Tags:

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?

like image 562
user1145280 Avatar asked Feb 04 '14 13:02

user1145280


People also ask

How do I check if a StringBuilder is null?

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

How do you do null check for StringBuilder in Java?

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.

How do I check if a StringBuffer is null?

so you can use the fact that StringBuffer. length() returns zero (or not) to check if the buffer is empty (or not).

Can we append null in StringBuilder?

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.


2 Answers

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");
}
like image 117
Kick Avatar answered Oct 29 '22 05:10

Kick


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.

like image 27
Bathsheba Avatar answered Oct 29 '22 06:10

Bathsheba