196

I want to perform some action ONLY IF my string has a meaningful value. So, I tried this.

if (!myString.equals("")) {
doSomething
}

and this

if (!myString.equals(null)) {
doSomething
}

and this

if ( (!myString.equals("")) && (!myString.equals(null))) {
doSomething
}

and this

if ( (!myString.equals("")) && (myString!=null)) {
doSomething
}

and this

if ( myString.length()>0) {
doSomething
}

And in all cases my program doSomething in spite on the fact that my string IS EMPTY. It equals to null. So, what is wrong with that?

ADDED:

I found the reason of the problem. The variable was declared as a string and, as a consequence, null assigned to this variable was transformed to "null"! So, if (!myString.equals("null")) works.

6
  • 2
    null doesn't have any methods, so also not equals(). If myString were null, how would you ever invoke a method on it? :) Commented Apr 8, 2010 at 17:17
  • 1
    May I suggest that you System.out.println(myString) immediately before the if-block so you can see what's there? Commented Apr 8, 2010 at 17:22
  • 1
    How do you know that "it equals to null"? Commented Apr 8, 2010 at 17:24
  • 7
    null assigned to this variable was transformed to "null" -- this is a terrible idea. Try to change this design if at all possible. Commented Apr 8, 2010 at 17:40
  • 9
    Yuck - I don't think checking whether (!myString.equals("null")) is the best solution. I suspect most would consider the point at which the string "null" was assigned to myString to be a bug. Commented Apr 8, 2010 at 17:41

28 Answers 28

255
if (myString != null && !myString.isEmpty()) {
  // doSomething
}

As further comment, you should be aware of this term in the equals contract:

From Object.equals(Object):

For any non-null reference value x, x.equals(null) should return false.

The way to compare with null is to use x == null and x != null.

Moreover, x.field and x.method() throws NullPointerException if x == null.

Sign up to request clarification or add additional context in comments.

4 Comments

You should do length check as opposed to equals for efficiency purposes. Check this link hanuska.blogspot.com/2006/08/empty-string.html
I would say you should do s.isEmpty() instead of s.length() == 0 for readability. Any difference in performance is negligible. I do agree that s.equals("") is terrible.
I agree on the readability. It depends whether we are using Java 5 vs Java 6 since isEmpty() is only in Java 6.
@CoolBeans: Good comment! I hadn't realized that! I'm a bit late to the Java party =)
34

If myString is null, then calling myString.equals(null) or myString.equals("") will fail with a NullPointerException. You cannot call any instance methods on a null variable.

Check for null first like this:

if (myString != null && !myString.equals("")) {
    //do something
}

This makes use of short-circuit evaluation to not attempt the .equals if myString fails the null check.

3 Comments

+1 for short-circuit; it's essential for the expression to work. However, you really should use .isEmpty() instead of .equals("").
Okay I meant to leave my comment on this post. lol. -> " You should do length check as opposed to equals for efficiency purposes. Check this link hanuska.blogspot.com/2006/08/empty-string.html "
@CoolBeans: Sure, and with Java 6 you could even do myString.isEmpty(). But at this level, readability trumps optimization, and people might be more used to reading myString.equals(""). (Or possibly not.)
26

Apache commons StringUtils.isNotEmpty is the best way to go.

1 Comment

or StringUtils.isEmpty() for checking the String is Null/Empty
15

If myString is in fact null, then any call to the reference will fail with a Null Pointer Exception (NPE). Since java 6, use #isEmpty instead of length check (in any case NEVER create a new empty String with the check).

if (myString != null &&  !myString.isEmpty()){
    doSomething();
}

Incidentally if comparing with String literals as you do, would reverse the statement so as not to have to have a null check, i.e,

if ("some string to check".equals(myString)){
  doSomething();
} 

instead of :

if (myString != null &&  myString.equals("some string to check")){
    doSomething();
}

2 Comments

Good point, but last two ifs are not equivalent. With myString = "abc", the middle one does not call doSomething but the third one does.
@rimsky that's fixed
11

WORKING !!!!

 if (myString != null && !myString.isEmpty()) {
        return true;
    }
    else {
        return false;
    }

Updated

For Kotlin we check if the string is null or not by following

return myString.isNullOrEmpty() // Returns `true` if this nullable String is either `null` or empty, false otherwise

return myString.isEmpty() // Returns `true` if this char sequence is empty (contains no characters), false otherwise

Comments

7

You need to check that the myString object is null:

if (myString != null) {
    doSomething
}

Comments

6

If your string is null, calls like this should throw a NullReferenceException:

myString.equals(null)

But anyway, I think a method like this is what you want:

public static class StringUtils
{
    public static bool isNullOrEmpty(String myString)
    {
         return myString == null || "".equals(myString);
    }
}

Then in your code, you can do things like this:

if (!StringUtils.isNullOrEmpty(myString))
{
    doSomething();
}

Comments

6

I would encourage using an existing utility, or creating your own method:

public static boolean isEmpty(String string) {
    return string == null || string.length() == 0;
}

Then just use it when you need it:

if (! StringUtils.isEmpty(string)) {
  // do something
}

As noted above, the || and && operators short circuit. That means as soon as they can determine their value they stop. So if (string == null) is true, the length part does not need to be evaluated, as the expression would always be true. Likewise with &&, where if the left side is false, the expression is always false and need not be evaluated further.

As an additional note, using length is generally a better idea than using .equals. The performance is slightly better (not much), and doesn't require object creation (though most compilers might optimize this out).

Comments

5

Try,

myString!=null && myString.length()>0

2 Comments

this is not possible if myString is null
this is pretty much possible when myString is null. You should know that when the left part of the && fails, the right expression will not be evaluated at all..
5
 if (myString != null && myString.length() > 0) {

        // your magic here

 }

Incidently, if you are doing much string manipulation, there's a great Spring class with all sorts of useful methods:

http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/StringUtils.html

Comments

5

Every time i have to deal with strings (almost every time) I stop and wonder which way is really the fastest way to check for an empty string. Of course the string.Length == 0 check should be the fastest since Length is a property and there shouldn't be any processing other than retrieving the value of the property. But then I ask myself, why is there a String.Empty? It should be faster to check for String.Empty than for length, I tell myself. Well i finnaly decided to test it out. I coded a small Windows Console app that tells me how long it takes to do a certain check for 10 million repitions. I checked 3 different strings: a NULL string, an Empty string, and a "" string. I used 5 different methods: String.IsNullOrEmpty(), str == null, str == null || str == String.Empty, str == null || str == "", str == null || str.length == 0. Below are the results:

String.IsNullOrEmpty()
NULL = 62 milliseconds
Empty = 46 milliseconds
"" = 46 milliseconds

str == null
NULL = 31 milliseconds
Empty = 46 milliseconds
"" = 31 milliseconds

str == null || str == String.Empty
NULL = 46 milliseconds
Empty = 62 milliseconds
"" = 359 milliseconds

str == null || str == ""
NULL = 46 milliseconds
Empty = 343 milliseconds
"" = 78 milliseconds

str == null || str.length == 0
NULL = 31 milliseconds
Empty = 63 milliseconds
"" = 62 milliseconds

According to these results, on average checking for str == null is the fastest, but might not always yield what we're looking for. if str = String.Empty or str = "", it results in false. Then you have 2 that are tied in second place: String.IsNullOrEmpty() and str == null || str.length == 0. Since String.IsNullOrEmpty() looks nicer and is easier (and faster) to write I would recommend using it over the other solution.

Comments

4

I'd do something like this:

( myString != null && myString.length() > 0 )
    ? doSomething() : System.out.println("Non valid String");
  • Testing for null checks whether myString contains an instance of String.
  • length() returns the length and is equivalent to equals("").
  • Checking if myString is null first will avoid a NullPointerException.

Comments

4

I been using StringUtil.isBlank(string)

It tests if a string is blank: null, emtpy, or only whitespace.

So this one is the best so far

Here is the orignal method from the docs

/**
    * Tests if a string is blank: null, emtpy, or only whitespace (" ", \r\n, \t, etc)
    * @param string string to test
    * @return if string is blank
    */
    public static boolean isBlank(String string) {
        if (string == null || string.length() == 0)
            return true;

        int l = string.length();
        for (int i = 0; i < l; i++) {
            if (!StringUtil.isWhitespace(string.codePointAt(i)))
                return false;
        }
        return true;
    } 

Comments

4

For me the best check if a string has any meaningful content in Java is this one:

string != null && !string.trim().isEmpty()

First you check if the string is null to avoid NullPointerException and then you trim all space characters to avoid checking strings that only have whitespaces and finally you check if the trimmed string is not empty, i.e has length 0.

Comments

3

This should work:

if (myString != null && !myString.equals(""))
    doSomething
}

If not, then myString likely has a value that you are not expecting. Try printing it out like this:

System.out.println("+" + myString + "+");

Using the '+' symbols to surround the string will show you if there is extra whitespace in there that you're not accounting for.

Comments

3

if(str.isEmpty() || str==null){ do whatever you want }

3 Comments

isEmpty is reversed.. if you call method on null object, you get NPE
If the string is null you get a null pointer exception, even before you check it is null. This code should never be used!
To keep code clean, usually best to detect error condition instead of wrapping lots of code in an if/else test. if (data == null || data.isEmpty()) { //barf }
3

Okay this is how datatypes work in Java. (You have to excuse my English, I am prob. not using the right vocab. You have to differentiate between two of them. The base datatypes and the normal datatypes. Base data types pretty much make up everything that exists. For example, there are all numbers, char, boolean etc. The normal data types or complex data types is everything else. A String is an array of chars, therefore a complex data type.

Every variable that you create is actually a pointer on the value in your memory. For example:

String s = new String("This is just a test");

the variable "s" does NOT contain a String. It is a pointer. This pointer points on the variable in your memory. When you call System.out.println(anyObject), the toString() method of that object is called. If it did not override toString from Object, it will print the pointer. For example:

public class Foo{
    public static void main(String[] args) {
        Foo f = new Foo();
        System.out.println(f);
    }
}

>>>>
>>>>
>>>>Foo@330bedb4

Everything behind the "@" is the pointer. This only works for complex data types. Primitive datatypes are DIRECTLY saved in their pointer. So actually there is no pointer and the values are stored directly.

For example:

int i = 123;

i does NOT store a pointer in this case. i will store the integer value 123 (in byte ofc).

Okay so lets come back to the == operator. It always compares the pointer and not the content saved at the pointer's position in the memory.

Example:

String s1 = new String("Hallo");
String s2 = new String("Hallo");

System.out.println(s1 == s2);

>>>>> false

This both String have a different pointer. String.equals(String other) however compares the content. You can compare primitive data types with the '==' operator because the pointer of two different objects with the same content is equal.

Null would mean that the pointer is empty. An empty primitive data type by default is 0 (for numbers). Null for any complex object however means, that object does not exist.

Greetings

Comments

1

I had this problem in android and i use this way (Work for me):

String test = null;
if(test == "null"){
// Do work
}

But in java code I use :

String test = null;
if(test == null){
// Do work
}

And :

private Integer compareDateStrings(BeanToDoTask arg0, BeanToDoTask arg1, String strProperty) {
    String strDate0 = BeanUtils.getProperty(arg0, strProperty);_logger.debug("strDate0 = " + strDate0);
    String strDate1 = BeanUtils.getProperty(arg1, strProperty);_logger.debug("strDate1 = " + strDate1);
    return compareDateStrings(strDate0, strDate1);
}

private Integer compareDateStrings(String strDate0, String strDate1) {
    int cmp = 0;
    if (isEmpty(strDate0)) {
        if (isNotEmpty(strDate1)) {
            cmp = -1;
        } else {
            cmp = 0;
        }
    } else if (isEmpty(strDate1)) {
        cmp = 1;
    } else {
        cmp = strDate0.compareTo(strDate1);
    }
    return cmp;
}

private boolean isEmpty(String str) {
    return str == null || str.isEmpty();
}
private boolean isNotEmpty(String str) {
    return !isEmpty(str);
}

Comments

1

I prefer to use:

if(!StringUtils.isBlank(myString)) { // checks if myString is whitespace, empty, or null
    // do something
}

Read StringUtils.isBlank() vs String.isEmpty().

Comments

1

In Android you can check this with utility method isEmpty from TextUtils,

public static boolean isEmpty(CharSequence str) {
    return str == null || str.length() == 0;
}

isEmpty(CharSequence str) method check both condition, for null and length.

Comments

1

If you are working in Android then you can use the simple TextUtils class. Check the following code:

if(!TextUtils.isEmpty(myString)){
 //do something
}

This is simple usage of code. Answer may be repeated. But is simple to have single and simple check for you.

Comments

1

I always use like this:

if (mystr != null && !mystr.isEmpty()){
  //DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}else {
  //DO WHATEVER YOU WANT OR LEAVE IT EMPTY
}

or you can copy this to your project:

private boolean isEmptyOrNull(String mystr){
    if (mystr != null && !mystr.isEmpty()){ return true; }
    else { return false; }
}

and just call it like :

boolean b = isEmptyOrNull(yourString);

it will return true if is empty or null.
b=true if is empty or null

or you can use try catch and catch when it is null.

Comments

0

I think that myString is not a string but an array of strings. Here is what you need to do:

String myNewString = join(myString, "")
if (!myNewString.equals(""))
{
    //Do something
}

1 Comment

My code is for processing. Processing is a java-based programming language. More information about join: processing.org/reference/join_.html .
0

You can check string equal to null using this:

String Test = null;
(Test+"").compareTo("null")

If the result is 0 then (Test+"") = "null".

1 Comment

this just creates an unnecessary string
0

I tried most of the examples given above for a null in an android app l was building and IT ALL FAILED. So l came up with a solution that worked anytime for me.

String test = null+"";
If(!test.equals("null"){
       //go ahead string is not null

}

So simply concatenate an empty string as l did above and test against "null" and it works fine. In fact no exception is thrown

3 Comments

No, that’s an absolutely terrible solution. The answers above work.
@KonradRudolph I actually tried some of these solutions above before arriving at my conclusion. I tried using these soluton in a recyclerview adapter and it did not give me the correct result until l came up with this answer.
I can confidently say that this means there’s something else wrong with your code, and you are merely fixing the symptoms, not the source of the error. Don’t take this the wrong way, but this is a typical case of cargo cult programming.
0

Exception may also help:

try {
   //define your myString
}
catch (Exception e) {
   //in that case, you may affect "" to myString
   myString="";
}

Comments

0

I'm using a function like this where I pass the get string result into it so I don't have to constantly check null and it either returns the string you passed back or empty if it's null:

public static String safeGet(String str) {
    try {
        if (str == null) throw new Exception();
        return "" + str;
    } catch (Exception e) {
        return "";
    }
}

1 Comment

This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From Review
-5

You have to check with null if(str != null).

3 Comments

Your solution was posted by other users years ago... What the point of repeating it?
i see non of the answers confirmed that is why i reply him
Right, he hasn't confirmed the answers since 2010, so you'll just repeat a previous answer and he will confirm your answer...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.