Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a string is empty or null in Java [duplicate]

Tags:

java

I'm parsing HTML data. The String may be null or empty, when the word to parse does not match.

So, I wrote it like this:

if(string.equals(null) || string.equals("")){     Log.d("iftrue", "seem to be true"); }else{     Log.d("iffalse", "seem to be false"); } 

When I delete String.equals(""), it does not work correctly.

I thought String.equals("") wasn't correct.

How can I best check for an empty String?

like image 957
user2027811 Avatar asked Feb 06 '13 04:02

user2027811


People also ask

How do you check if a string is not null or empty in Java?

Using the isEmpty() Method The isEmpty() method returns true or false depending on whether or not our string contains any text. It's easily chainable with a string == null check, and can even differentiate between blank and empty strings: String string = "Hello there"; if (string == null || string. isEmpty() || string.

How do I check if a string is empty or null?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

What is isEmpty ()?

However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name. Remarks. IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False.

Is string empty Java?

isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. The isEmpty() method of String class is included in java string since JDK 1.6. In other words, you can say that this method returns true if the length of the string is 0.


2 Answers

Correct way to check for null or empty or string containing only spaces is like this:

if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ } 
like image 65
Pradeep Simha Avatar answered Oct 12 '22 05:10

Pradeep Simha


You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.

Example:

System.out.println(StringUtils.isEmpty("")); // true System.out.println(StringUtils.isEmpty(null)); // true 

Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).

Example:

System.out.println(Strings.isNullOrEmpty("")); // true System.out.println(Strings.isNullOrEmpty(null)); // true 
like image 39
Makoto Avatar answered Oct 12 '22 06:10

Makoto