558

How can I check whether a string is not null and not empty?

public void doStuff(String str)
{
    if (str != null && str != "**here I want to check the 'str' is empty or not**")
    {
        /* handle empty string */
    }
    /* ... */
}
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
  • 8
    You should probably use `PreparedStatement` and such instead of constructing an SQL query by string concatenation primitives. Avoids all kinds of injection vulnerabilities, much more readable, etc. – polygenelubricants Aug 30 '10 at 08:09
  • 2
    You can create class that will check for null values or null object. That will help you improving reuse-ability.. http://stackoverflow.com/a/16833309/1490962 – Bhushankumar Lilapara May 30 '13 at 10:11
  • This condition can be expressed as a *java.util.function.Predicate* in the following way `Predicate.isEqual(null).or(String::isEmpty).negate()` as explained [here](https://stackoverflow.com/a/74649555/17949945). – Alexander Ivanchenko Dec 02 '22 at 12:18

35 Answers35

995

What about isEmpty() ?

if(str != null && !str.isEmpty())

Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.

Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.


To ignore whitespace as well:

if(str != null && !str.trim().isEmpty())

(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces)

Wrapped in a handy function:

public static boolean empty( final String s ) {
  // Null-safe, short-circuit evaluation.
  return s == null || s.trim().isEmpty();
}

Becomes:

if( !empty( str ) )
Pshemo
  • 122,468
  • 25
  • 185
  • 269
Colin Hebert
  • 91,525
  • 15
  • 160
  • 151
  • 83
    Note that `isEmpty()` appears to require a String instance (non-static). Invoking this on a null reference will throw a NullPointerException. – James P. Aug 14 '11 at 12:22
  • 39
    Or if(str != null && !str.trim().isEmpty()), to ignore whitespace. – PapaFreud Nov 21 '13 at 17:15
  • if((txt.getText().length()) == 0 ) // get element from layout – jruzafa Apr 28 '14 at 20:11
  • 37
    I'd recommend to use `TextUtils.isEmpty(String)` to check is string empty or null. Nice and short. The TextUtils class is a part of Android SDK. – George Maisuradze Nov 19 '14 at 21:26
  • boolean check = (yourstring != null) ? (yourstring.length() > 0 ? true : false) : false; – user1154390 Nov 20 '14 at 17:17
  • 1
    @user1154390: sometimes its worth explicitly using true and false for clarity, but when condition returns true for true and false for false, its unnecessary complexity. Simply say `(str != null && str.length() > 0)`. – ToolmakerSteve Aug 27 '15 at 23:37
  • Need to use a simple Predicate to be on safe side. Predicate isBlank = str -> str != null && str.isBlank(); – Anver Sadhat Oct 17 '18 at 14:34
243

Use org.apache.commons.lang.StringUtils

I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:

import org.apache.commons.lang.StringUtils;

if (StringUtils.isNotBlank(str)) {
    ...
} 

if (StringUtils.isBlank(str)) {
    ...
} 
Community
  • 1
  • 1
Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273
  • 22
    isn't Apache commons-lang an overkill if you can just use isEmpty? Just curious. – zengr Aug 30 '10 at 08:26
  • 21
    @zengr - no, because you most certainly would use other things as well :) – Bozho Aug 30 '10 at 08:30
  • 2
    @zengr Indeed, if you only use `isEmpty` or `isBlank`, maybe it is not usefull to include a third-party library. You can simply create your own utility class to provide such method. However, as Bozho explain, the `commons-lang` project provide many usefull methods! – Romain Linsolas Aug 30 '10 at 08:40
  • 16
    Because `StringUtils.isNotBlank(str)` does the null-checking as well. – sdesciencelover Jan 30 '13 at 14:25
  • 3
    If you use Spring Framework, this could be ALREADY bundled in the jars of the framework. – linuxunil Oct 25 '18 at 17:53
  • 1
    If your app is already using this Apache Commons then its fine. Note there is Apache Commons lang3 `org.apache.commons.lang3.StringUtils.isNotBlank` – javaPlease42 Mar 04 '21 at 18:40
106

Just adding Android in here:

import android.text.TextUtils;

if (!TextUtils.isEmpty(str)) {
...
}
phreakhead
  • 14,721
  • 5
  • 39
  • 40
  • 1
    @staticx, The StringUtils method changed in Lang version 2.0. It no longer trims the CharSequence. That functionality is available in isBlank(). – Nick Dec 11 '14 at 00:08
52

To add to @BJorn and @SeanPatrickFloyd The Guava way to do this is:

Strings.nullToEmpty(str).isEmpty(); 
// or
Strings.isNullOrEmpty(str);

Commons Lang is more readable at times but I have been slowly relying more on Guava plus sometimes Commons Lang is confusing when it comes to isBlank() (as in what is whitespace or not).

Guava's version of Commons Lang isBlank would be:

Strings.nullToEmpty(str).trim().isEmpty()

I will say code that doesn't allow "" (empty) AND null is suspicious and potentially buggy in that it probably doesn't handle all cases where is not allowing null makes sense (although for SQL I can understand as SQL/HQL is weird about '').

Adam Gent
  • 47,843
  • 23
  • 153
  • 203
  • second Guava too. Guava follows a convention of plural static classes. For String, try Strings for static methods like isNullOrEmpty(str). – Thupten Jun 29 '15 at 14:01
35
str != null && str.length() != 0

alternatively

str != null && !str.equals("")

or

str != null && !"".equals(str)

Note: The second check (first and second alternatives) assumes str is not null. It's ok only because the first check is doing that (and Java doesn't does the second check if the first is false)!

IMPORTANT: DON'T use == for string equality. == checks the pointer is equal, not the value. Two strings can be in different memory addresses (two instances) but have the same value!

helios
  • 13,574
  • 2
  • 45
  • 55
  • thanks...the str.length() worked for me. My case was that i'm getting the values from the array after querying from the database. Even if the data was empty, when i did the str.length it was giving "1" length. Very strange but thanks for showing me this. – arn-arn Mar 05 '15 at 19:17
  • That has to do with the internals of the database. Either it's a char field instead of a varchar field (so it pads with spaces) or the database doesn't like empty strings. I guess the best is to preprocess those values after/while querying (in the data access later of the app). – helios Mar 12 '15 at 20:33
  • I think checking the length is better than 'equals' because it's an O(1) operation since the length is cached in case of String. – bluelurker Dec 09 '15 at 17:08
29

Almost every library I know defines a utility class called StringUtils, StringUtil or StringHelper, and they usually include the method you are looking for.

My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the

  1. StringUtils.isEmpty(String) and the
  2. StringUtils.isBlank(String) method

(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)

There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.


Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string) method.

troig
  • 7,072
  • 4
  • 37
  • 63
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • I would like to ask why you recommend now this? I would like to know if there is a difference between the Strings.isNullOrEmpty(string) and StringUtils.isEmpty(String) – vicangel Aug 20 '19 at 13:01
  • @vicangel Apache Commons methods are full of assumptions and things I didn't ask for. With Guava, I get exactly what I asked for and nothing more or less – Sean Patrick Floyd Aug 21 '19 at 17:07
25

This works for me:

import com.google.common.base.Strings;

if (!Strings.isNullOrEmpty(myString)) {
       return myString;
}

Returns true if the given string is null or is the empty string.

Consider normalizing your string references with nullToEmpty. If you do, you can use String.isEmpty() instead of this method, and you won't need special null-safe forms of methods like String.toUpperCase either. Or, if you'd like to normalize "in the other direction," converting empty strings to null, you can use emptyToNull.

Javatar
  • 2,518
  • 1
  • 31
  • 43
16

There is a new method in : String#isBlank

Returns true if the string is empty or contains only white space codepoints, otherwise false.

jshell> "".isBlank()
$7 ==> true

jshell> " ".isBlank()
$8 ==> true

jshell> " ! ".isBlank()
$9 ==> false

This could be combined with Optional to check if string is null or empty

boolean isNullOrEmpty = Optional.ofNullable(str).map(String::isBlank).orElse(true);

String#isBlank

Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
10

How about:

if(str!= null && str.length() != 0 )
codaddict
  • 445,704
  • 82
  • 492
  • 529
  • 1
    throws NullPointerException if str is NULL. – Mindwin Remember Monica May 15 '13 at 15:19
  • 14
    @Mindwin That's not true. It will not execute the code to the right of the `&&` if str == null, thus preventing a NullPointerException. (Source: I just tried) – Zach Lysobey Aug 14 '13 at 21:57
  • 1
    I stand corrected. Won't delete the comment out of shame so Zach and GI Joe won't be left with responses hanging out of nowhere. Lolz. BUT its nice to know that, this skipping might cause logical failures if you do something else other than just test stuff and return a boolean on the skipped method calls. – Mindwin Remember Monica Feb 18 '14 at 12:15
  • 3
    @Mindwin It's nice to know how the language you are using actually works. If you don't understand short-circuit evaluation, either don't use it or, better still, learn about it. – user207421 Jun 24 '16 at 02:29
8

For completeness: If you are already using the Spring framework, the StringUtils provide the method

org.springframework.util.StringUtils.hasLength(String str)

Returns: true if the String is not null and has length

as well as the method

org.springframework.util.StringUtils.hasText(String str)

Returns: true if the String is not null, its length is greater than 0, and it does not contain whitespace only

AntiTiming
  • 2,094
  • 3
  • 22
  • 33
8

Returns true or false based on input

Predicate<String> p = (s)-> ( s != null && !s.isEmpty());
p.test(string);
araknoid
  • 3,065
  • 5
  • 33
  • 35
7

You should use org.apache.commons.lang3.StringUtils.isNotBlank() or org.apache.commons.lang3.StringUtils.isNotEmpty. The decision between these two is based on what you actually want to check for.

The isNotBlank() checks that the input parameter is:

  • not Null,
  • not the empty string ("")
  • not a sequence of whitespace characters (" ")

The isNotEmpty() checks only that the input parameter is

  • not null
  • not the Empty String ("")
gprasant
  • 15,589
  • 9
  • 43
  • 57
7

You can use the functional style of checking:

Optional.ofNullable(str)
    .filter(s -> !(s.trim().isEmpty()))
    .ifPresent(result -> {
       // your query setup goes here
    });
slartidan
  • 20,403
  • 15
  • 83
  • 131
pilot
  • 866
  • 11
  • 16
  • 2
    I would recommend using a map for the trim e.g: Optional.ofNullable(str) .map(String::trim) .filter(String::isEmpty) .ifPresent(this::setStringMethod); – bachph Aug 11 '17 at 08:55
7

Use Apache StringUtils' isNotBlank method like

StringUtils.isNotBlank(str)

It will return true only if the str is not null and is not empty.

arsenal
  • 23,366
  • 85
  • 225
  • 331
A Null Pointer
  • 2,261
  • 3
  • 26
  • 28
5

If you don't want to include the whole library; just include the code you want from it. You'll have to maintain it yourself; but it's a pretty straight forward function. Here it is copied from commons.apache.org

    /**
 * <p>Checks if a String is whitespace, empty ("") or null.</p>
 *
 * <pre>
 * StringUtils.isBlank(null)      = true
 * StringUtils.isBlank("")        = true
 * StringUtils.isBlank(" ")       = true
 * StringUtils.isBlank("bob")     = false
 * StringUtils.isBlank("  bob  ") = false
 * </pre>
 *
 * @param str  the String to check, may be null
 * @return <code>true</code> if the String is null, empty or whitespace
 * @since 2.0
 */
public static boolean isBlank(String str) {
    int strLen;
    if (str == null || (strLen = str.length()) == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if ((Character.isWhitespace(str.charAt(i)) == false)) {
            return false;
        }
    }
    return true;
}
Tom
  • 59
  • 1
  • 2
3

test equals with an empty string and null in the same conditional:

if(!"".equals(str) && str != null) {
    // do stuff.
}

Does not throws NullPointerException if str is null, since Object.equals() returns false if arg is null.

the other construct str.equals("") would throw the dreaded NullPointerException. Some might consider bad form using a String literal as the object upon wich equals() is called but it does the job.

Also check this answer: https://stackoverflow.com/a/531825/1532705

Community
  • 1
  • 1
Mindwin Remember Monica
  • 1,469
  • 2
  • 20
  • 35
3

Simple solution :

private boolean stringNotEmptyOrNull(String st) {
    return st != null && !st.isEmpty();
}
Shweta
  • 924
  • 14
  • 23
2

I've made my own utility function to check several strings at once, rather than having an if statement full of if(str != null && !str.isEmpty && str2 != null && !str2.isEmpty). This is the function:

public class StringUtils{

    public static boolean areSet(String... strings)
    {
        for(String s : strings)
            if(s == null || s.isEmpty)
                return false;

        return true;
    }   

}

so I can simply write:

if(!StringUtils.areSet(firstName,lastName,address)
{
    //do something
}
W.K.S
  • 9,787
  • 15
  • 75
  • 122
  • 2
    Would be nicer to use the signature: `areSet(String... strings)` can then be invoked without the array creation: `if(!StringUtils.areSet(firstName, lastName, address))` – weston Feb 11 '14 at 14:12
2

You can use StringUtils.isEmpty(), It will result true if the string is either null or empty.

 String str1 = "";
 String str2 = null;

 if(StringUtils.isEmpty(str)){
     System.out.println("str1 is null or empty");
 }

 if(StringUtils.isEmpty(str2)){
     System.out.println("str2 is null or empty");
 }

will result in

str1 is null or empty

str2 is null or empty

Vivek Vermani
  • 1,934
  • 18
  • 45
2

As seanizer said above, Apache StringUtils is fantastic for this, if you were to include guava you should do the following;

public List<Employee> findEmployees(String str, int dep) {
 Preconditions.checkState(StringUtils.isNotBlank(str), "Invalid input, input is blank or null");
 /** code here **/
}

May I also recommend that you refer to the columns in your result set by name rather than by index, this will make your code much easier to maintain.

BjornS
  • 1,004
  • 8
  • 19
  • No need to use apache commons from guava though, there is a Strings class in guava too: http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Strings.html – Sean Patrick Floyd Aug 30 '10 at 08:37
  • I added some Guava examples for novice Java users that land on this question: http://stackoverflow.com/a/13146903/318174 . – Adam Gent Oct 30 '12 at 20:21
2

In case you are using Java 8 and want to have a more Functional Programming approach, you can define a Function that manages the control and then you can reuse it and apply() whenever is needed.

Coming to practice, you can define the Function as

Function<String, Boolean> isNotEmpty = s -> s != null && !"".equals(s)

Then, you can use it by simply calling the apply() method as:

String emptyString = "";
isNotEmpty.apply(emptyString); // this will return false

String notEmptyString = "StackOverflow";
isNotEmpty.apply(notEmptyString); // this will return true

If you prefer, you can define a Function that checks if the String is empty and then negate it with !.

In this case, the Function will look like as :

Function<String, Boolean> isEmpty = s -> s == null || "".equals(s)

Then, you can use it by simply calling the apply() method as:

String emptyString = "";
!isEmpty.apply(emptyString); // this will return false

String notEmptyString = "StackOverflow";
!isEmpty.apply(notEmptyString); // this will return true
araknoid
  • 3,065
  • 5
  • 33
  • 35
  • This is how I like to do it, when I'm worried about performance cost or side-effects, and no imports readily to hand. – david.pfx Mar 27 '20 at 10:32
2

With Java 8 Optional you can do:

public Boolean isStringCorrect(String str) {
    return Optional.ofNullable(str)
            .map(String::trim)
            .map(string -> !str.isEmpty())
            .orElse(false);
}

In this expression, you will handle Strings that consist of spaces as well.

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
Johnny
  • 14,397
  • 15
  • 77
  • 118
2

If you are using Spring Boot then below code will do the Job

StringUtils.hasLength(str)
Avinash
  • 812
  • 1
  • 8
  • 22
2

To check if a string is not empty you can check if it is null but this doesn't account for a string with whitespace. You could use str.trim() to trim all the whitespace and then chain .isEmpty() to ensure that the result is not empty.

if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
Anton Kesy
  • 119
  • 7
Raviraj
  • 906
  • 9
  • 14
1

I would advise Guava or Apache Commons according to your actual need. Check the different behaviors in my example code:

import com.google.common.base.Strings;
import org.apache.commons.lang.StringUtils;

/**
 * Created by hu0983 on 2016.01.13..
 */
public class StringNotEmptyTesting {
  public static void main(String[] args){
        String a = "  ";
        String b = "";
        String c=null;

    System.out.println("Apache:");
    if(!StringUtils.isNotBlank(a)){
        System.out.println(" a is blank");
    }
    if(!StringUtils.isNotBlank(b)){
        System.out.println(" b is blank");
    }
    if(!StringUtils.isNotBlank(c)){
        System.out.println(" c is blank");
    }
    System.out.println("Google:");

    if(Strings.isNullOrEmpty(Strings.emptyToNull(a))){
        System.out.println(" a is NullOrEmpty");
    }
    if(Strings.isNullOrEmpty(b)){
        System.out.println(" b is NullOrEmpty");
    }
    if(Strings.isNullOrEmpty(c)){
        System.out.println(" c is NullOrEmpty");
    }
  }
}

Result:
Apache:
a is blank
b is blank
c is blank
Google:
b is NullOrEmpty
c is NullOrEmpty

BlondCode
  • 4,009
  • 1
  • 19
  • 18
1

Simply, to ignore white space as well:

if (str == null || str.trim().length() == 0) {
    // str is empty
} else {
    // str is not empty
}
simhumileco
  • 31,877
  • 16
  • 137
  • 115
1

Consider the below example, I have added 4 test cases in main method. three test cases will pass when you follow above commented snipts.

public class EmptyNullBlankWithNull {
    public static boolean nullEmptyBlankWithNull(String passedStr) {
        if (passedStr != null && !passedStr.trim().isEmpty() && !passedStr.trim().equals("null")) {
            // TODO when string is null , Empty, Blank
            return true;
        }else{
            // TODO when string is null , Empty, Blank
            return false;
        }
    }

    public static void main(String[] args) {
        String stringNull = null; // test case 1
        String stringEmpty = ""; // test case 2
        String stringWhiteSpace = "  "; // test case 3
        String stringWhiteSpaceWithNull = " null"; // test case 4
        System.out.println("TestCase result:------ "+nullEmptyBlankWithNull(stringWhiteSpaceWithNull));
        
    }
}

BUT test case 4 will return true(it has white space before null) which is wrong:

String stringWhiteSpaceWithNull = " null"; // test case 4

We have to add below conditions to make it work propper:

!passedStr.trim().equals("null")
1

TL;DR

java.util.function.Predicate is a Functional interface representing a boolean-valued Function.

Predicate offers several static and default methods which allow to perform logical operations AND &&, OR ||, NOT ! and chain conditions in a fluent way.

Logical condition "not empty && not null" can be expressed in the following way:

Predicate.not(Predicate.<String>isEqual(null).or(String::isEmpty));

Or, alternatively:

Predicate.<String>isEqual(null).or(String::isEmpty).negate();

Or:

Predicate.<String>isEqual(null).or(""::equals).negate();

Predicate.equal() is your friend

Static method Predicate.isEqual() expects a reference to the target object for equality comparison (an empty string in this case). This comparison is not hostile to null, which means isEqual() performs a null-check internally as well as utility method Objects.equals(Object, Object), so that comparison of null and null would return true without raising an exception.

A quote from the Javadoc:

Returns:

a predicate that tests if two arguments are equal according to Objects.equals(Object, Object)

The predicate the compares the given element against the null can be written as:

Predicate.isEqual(null)

Predicate.or() OR ||

Default method Predicate.or() allows chaining the conditions relationship among which can be expressed through logical OR ||.

That's how we can combine the two conditions: empty || null

Predicate.isEqual(null).or(String::isEmpty)

Now we need to negate this predicate

Predicate.not() & Predicate.negete()

To perform the logical negation, we have two options: static method not() and default method negate().

Here's how resulting predicates might be written:

public static final Predicate<String> NON_EMPTY_NON_NULL =
    Predicate.<String>isEqual(null).or(String::isEmpty).negate();

Note that in this case the type of the predicate Predicate.isEqual(null) would be inferred as Predicate<Object> since null gives no clue to the compiler what should be the type of the argument, and we can resolve this issue using a so-called Type-witness <String>isEqual().

Or, alternatively

public static final Predicate<String> NON_EMPTY_NON_NULL =
    Predicate.not(Predicate.<String>isEqual(null).or(String::isEmpty));

*Note: String::isEmpty can be also written as ""::equals, and if you need to check whether the string is Blank (contains various forms of unprintable characters or empty) you can use method reference String::isBlank. And if you need to verify a few more conditions, you can add as many as you need by chaining them via or() and and() methods.

Usage Example

Predicate is used an argument of such method as Stream.filter(), Collection.removeIf(), Collectors.partitioningBy(), etc. and you can create your custom ones.

Consider the following example:

List<String> strings = Stream.of("foo", "bar", "", null, "baz")
    .filter(NON_EMPTY_NON_NULL)
    .map("* "::concat) // append a prefix to make sure that empty string can't sneak in
    .toList();
        
strings.forEach(System.out::println);

Output:

* foo
* bar
* baz
Alexander Ivanchenko
  • 25,667
  • 5
  • 22
  • 46
  • `public static final Predicate NON_EMPTY_NON_NULL = Predicate.not(Predicate.isEqual(null).or(String::isEmpty));` returns "Non-static method cannot be referenced from a static context" – mellow-yellow Mar 08 '23 at 00:18
  • apparently, you can fix the above by adding `.isEqual` like this `public static final Predicate NON_EMPTY_NON_NULL = Predicate.not(Predicate.isEqual(null).or(String::isEmpty));` – mellow-yellow Mar 08 '23 at 01:38
  • @mellow-yellow You're right, without a type-witness the type of `Predicate.isEqual(null)` would be inferred by the compiler as `Predicate extends Object>`, hence we need to provide the type explicitly. Amended. – Alexander Ivanchenko Mar 09 '23 at 13:38
0

If you use Spring framework then you can use method:

org.springframework.util.StringUtils.isEmpty(@Nullable Object str);

This method accepts any Object as an argument, comparing it to null and the empty String. As a consequence, this method will never return true for a non-null non-String object.

Taras Melnyk
  • 3,057
  • 3
  • 38
  • 34
  • 1
    Note that the documentation for `StringUtils` explicitly states "Mainly for internal use within the framework; consider Apache's Commons Lang for a more comprehensive suite of String utilities." – Fredrik Jonsén Nov 28 '18 at 09:24
0

To check on if all the string attributes in an object is empty(Instead of using !=null on all the field names following java reflection api approach

private String name1;
private String name2;
private String name3;

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this) != null) {
                return false;
            }
        } catch (Exception e) {
            System.out.println("Exception occurred in processing");
        }
    }
    return true;
}

This method would return true if all the String field values are blank,It would return false if any one values is present in the String attributes

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
Lokeshkumar R
  • 575
  • 5
  • 13
0

I've encountered a situation where I must check that "null" (as a string) must be regarded as empty. Also white space and an actual null must return true. I've finally settled on the following function...

public boolean isEmpty(String testString) {
  return ((null==testString) || "".equals((""+testString).trim()) || "null".equals((""+testString).toLowerCase()));
}
Dave
  • 3,093
  • 35
  • 32
0

In case you need to validate your method parameters you can use follow simple method

public class StringUtils {

    static boolean anyEmptyString(String ... strings) {
        return Stream.of(strings).anyMatch(s -> s == null || s.isEmpty());
    }

}

Example:

public String concatenate(String firstName, String lastName) {
    if(StringUtils.anyBlankString(firstName, lastName)) {
        throw new IllegalArgumentException("Empty field found");
    }
    return firstName + " " + lastName;
}
Marco Montel
  • 581
  • 7
  • 13
0

If anyone using springboot, then the following option might be helpful,

import static org.springframework.util.StringUtils.hasLength;
if (hasLength(str)) {
  // do stuff
}

forhadmethun
  • 535
  • 5
  • 16
-1

The better way to handle null in the string is,

str!=null && !str.equalsIgnoreCase("null") && !str.isEmpty()

In short,

str.length()>0 && !str.equalsIgnoreCase("null")
-1
import android.text.TextUtils;

if (!TextUtils.isEmpty(str)||!str.equalsIgnoreCase("") {
    ...
}
Edgar H
  • 1,376
  • 2
  • 17
  • 31
Afroz Ahmad
  • 69
  • 10
  • 1
    Adding a few words of explanation is better than just some code. For example, why did you import a library? – Edgar H May 10 '19 at 07:35