Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Java by (3.4k points)

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 */

    }

    /* ... */

}

1 Answer

0 votes
by (3.5k points)

You can try isEmpty() 

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

Be certain to use the parts of && in this sequence, because java will not continue to evaluate the second part if the first part of && deserts, thus assuring you won't get a null pointer deviation of str.isEmpty() if str is null.

Beware, it's only likely since Java SE 1.6. You have to examine str.length() == 0 on earlier versions.

To neglect whitespace as well:

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

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

Encased in a handy function:

public static boolean empty( closing String s ) {

  // it's Null-safe and also short-circuit evaluation.

  return s == null || s.trim().isEmpty();

}

Becomes:

if( !empty( str ) )

Related questions

0 votes
1 answer
0 votes
2 answers
asked Jul 9, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...