193

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.

Roman
  • 124,451
  • 167
  • 349
  • 456
  • 2
    `null` doesn't have any methods, so also not `equals()`. If `myString` were `null`, how would you ever invoke a method on it? :) – BalusC Apr 08 '10 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? – Michael Myers Apr 08 '10 at 17:22
  • 1
    How do you know that "it equals to `null`"? – Richard JP Le Guen Apr 08 '10 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. – polygenelubricants Apr 08 '10 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. – Bert F Apr 08 '10 at 17:41
  • 1
    I don't want anyone to get confused like I did so, for clarification:when no value is assigned to a string it does not get a value of "null" but a value of null (with no paranthesis, which basically means nothing is in there) the solution provided in the "added section of the question is very specific to Roman's program. – Atlantis Oct 12 '14 at 10:35

28 Answers28

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

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • 2
    You should do length check as opposed to equals for efficiency purposes. Check this link http://hanuska.blogspot.com/2006/08/empty-string.html – CoolBeans Apr 08 '10 at 17:33
  • 7
    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. – polygenelubricants Apr 08 '10 at 17:36
  • 6
    I agree on the readability. It depends whether we are using Java 5 vs Java 6 since isEmpty() is only in Java 6. – CoolBeans Apr 08 '10 at 17:44
  • @CoolBeans: Good comment! I hadn't realized that! I'm a bit late to the Java party =) – polygenelubricants Apr 08 '10 at 17:51
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.

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
  • 1
    +1 for short-circuit; it's essential for the expression to work. However, you really should use `.isEmpty()` instead of `.equals("")`. – polygenelubricants Apr 08 '10 at 17:42
  • 1
    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 Apr 08 '10 at 17:42
  • @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.) – Michael Myers Apr 08 '10 at 18:41
27

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

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
kedar
  • 273
  • 4
  • 9
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();
}
pavi2410
  • 1,220
  • 2
  • 12
  • 16
corm
  • 151
  • 1
  • 2
10

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
Salman Nazir
  • 2,759
  • 2
  • 28
  • 42
7

You need to check that the myString object is null:

if (myString != null) {
    doSomething
}
dur
  • 15,689
  • 25
  • 79
  • 125
WhirlWind
  • 13,974
  • 3
  • 42
  • 42
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).

Matt
  • 11,523
  • 2
  • 23
  • 33
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();
}
Andy White
  • 86,444
  • 48
  • 176
  • 211
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.

ldsant
  • 51
  • 1
  • 1
5

Try,

myString!=null && myString.length()>0
bragboy
  • 34,892
  • 30
  • 114
  • 171
  • this is not possible if myString is null – hsmit Jan 06 '11 at 12:16
  • 5
    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.. – bragboy Jan 06 '11 at 20:07
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

Richard H
  • 38,037
  • 37
  • 111
  • 138
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.
James P.
  • 19,313
  • 27
  • 97
  • 155
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;
    } 
Atiq
  • 14,435
  • 6
  • 54
  • 69
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.

gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
3

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

Moe
  • 197
  • 6
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.

elduff
  • 1,178
  • 3
  • 14
  • 22
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

Luecx
  • 160
  • 1
  • 12
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);
}
A.A
  • 1,138
  • 1
  • 16
  • 29
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().

Community
  • 1
  • 1
k_rollo
  • 5,304
  • 16
  • 63
  • 95
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.

Dovydas Šopa
  • 2,282
  • 8
  • 26
  • 34
NSK
  • 251
  • 3
  • 10
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.

Manmohan Soni
  • 6,472
  • 2
  • 23
  • 29
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.

Web.11
  • 406
  • 2
  • 8
  • 23
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
}
mimit
  • 39
  • 6
  • My code is for processing. Processing is a java-based programming language. More information about join: https://processing.org/reference/join_.html . – mimit May 11 '15 at 17:52
0

You can check string equal to null using this:

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

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

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
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

CanCoder
  • 1,073
  • 14
  • 20
  • 1
    No, that’s an absolutely terrible solution. The answers above work. – Konrad Rudolph Jul 29 '16 at 14:31
  • @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. – CanCoder Aug 02 '16 at 13:50
  • 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](https://en.wikipedia.org/wiki/Cargo_cult_programming). – Konrad Rudolph Aug 02 '16 at 13:55
0

Exception may also help:

try {
   //define your myString
}
catch (Exception e) {
   //in that case, you may affect "" to myString
   myString="";
}
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 "";
    }
}
BoonBucket
  • 21
  • 2
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32599687) – user-id-14900042 Sep 03 '22 at 08:02
-5

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

ketan
  • 19,129
  • 42
  • 60
  • 98