Search code examples
javastringbuilder

How to check null on StringBuilder?


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?


Solution

  • 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");
    }