Java Strings: Testing if a String is Empty or Blank

Java Strings: Testing if a String is Empty or Blank

Learn to test if a String is Empty or Blank

Introduction

In this short tutorial, we'll go through some of the ways to check if a string is blank or empty.

1. Check if a String is Empty

A string is empty if it's length is 0. To test if a string is empty, we use the isEmpty() method.

Here is an example to test if a string is empty:

@Test
void stringIsEmpty() {
  // Test if a String is Empty.
  // Test will return true because the string is empty.
  assertTrue("".isEmpty());
}

Here is an example to test if a string is not empty:

@Test
void stringNotEmpty() {
    // Test if a String is Not Empty.
    // Test will return false because the sting was a space.
    assertFalse(" ".isEmpty());
}

2. Check if a String is Blank

A string is blank if it contains only whitespaces. To test if a string is blank, we use the isBlank() method.

Here is a example to test if a string is blank:

@Test
void stringIsBlank() {
    // Test if the String is Blank.
    // Test will return true because the string only contains whitespaces.
    assertTrue(" ".isBlank());
}

Here is an example to test if a string is not blank:

@Test                                                                                             
void stringNotBlank() {                                                                           
    // Test is the String is not Blank.                                                           
    // Test will return false because the string contains other elements besides whitespaces.     
    assertFalse(" Test ".isBlank());                                                              
} 

Conclusion

In this short tutorial, you learned how to check if a string is empty or blank. You can learn more about Java strings here.

Did you like it? Why don't you try also...

Split Strings in Java

Split Strings in Java

Learn how to split strings in Java

Java Strings: Basic String Methods Part 1

Java Strings: Basic String Methods Part 1

Learn the most common Java String Methods.

Java String: Title Case Format

Java String: Title Case Format

Learn How to Convert Java String to Title Case Format