Always use length() instead of equals() to check empty string in java

If we need to check, If the string is Empty, Then do not use this way :  string1.equals(“”)

Best way to check if string is empty or not is to use length() method. This method simply return the count of characters inside char array which constitutes the string. If the count or length is 0; you can safely conclude that string is empty.

public boolean isEmpty(String str)
{
return str.equals(“”); //NEVER do this
}

public boolean isEmpty(String str)
{
return str.length()==0; //Correct way to check empty
}
PS : From JAVA 6 onwards, isEmpty() function is available in String class itself. Please use this function directly.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>