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

Change the Server Port that a Spring Boot App is running on

Change the Server Port that a Spring Boot App is running on

Learn how to change the server port that a spring boot application is running on.

Fill Java Array With The Same Values

Fill Java Array With The Same Values

Learn How To Fill a Java Array With All The Same Values.

Java How to Remove the First Character from a String.

Java How to Remove the First Character from a String.

Learn How to Remove the First Character From a String.