DEV Community

Cover image for java check if the string is empty.
jacob777baltimore
jacob777baltimore

Posted on

java check if the string is empty.

Java program to check if a string is empty or null:

In the above program, we check that the isEmpty() method will only check whether the String is empty or not. If the user wants to check whether the given String is null or empty then you can do this in following ways;

public class Example{

   public static void main(String args[]){ 

               String str1 = null;

               String str2 = "beginners book"; 

               if(str1 == null || str1.isEmpty()){

                  System.out.println("String str1 is empty or null");

               }

               else{

                  System.out.println(str1);

               }

               if(str2 == null || str2.isEmpty()){

                  System.out.println("String str2 is empty or null"); 

               }

               else{

                  System.out.println(str2);

               }

   }

}
Enter fullscreen mode Exit fullscreen mode

Read more

Output

String str1 is empty or null

beginners book
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
nyorja profile image
Rod Fetalvero

IMHO I will use StringUtils by Apache Commons