Java Program to Check if a String is Empty or Null

JavaCampus InterviewServer Side ProgrammingProgramming

In this article, we will understand how to check if a string is empty or null. String is a datatype that contains one or more characters and is enclosed in double quotes(“ ”).

Below is a demonstration of the same −

Suppose our input is

Input string: null

The desired output would be

The string is a null string

Algorithm

Step 1 - START
Step 2 - Declare a string namely input_string.
Step 3 - Define the values.
Step 4 - Using an if-loop, compute input_string == null. If true, the string is null, else the string is not null.
Step 5 - Display the result
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

public class Demo {
   public static void main(String[] args) {
      String input_string = null;
      System.out.println("The string is defined as: " +input_string);
      if (input_string == null) {
         System.out.println("\nThe string is a null string");
      }
      else if(input_string.isEmpty()){
         System.out.println("\nThe string is an empty string");
      } else {
         System.out.println("\nThe string is neither empty nor null string");
      }
   }
}

Output

The string is defined as: null

The string is a null string

Example 2

Here, we encapsulate the operations into functions exhibiting object-oriented programming.

public class Demo {
   static void isNullEmpty(String input_string) {
      if (input_string == null) {
         System.out.println("\nThe string is a null string");
      }
      else if(input_string.isEmpty()){
         System.out.println("\nThe string is an empty string");
      } else {
         System.out.println("\nThe string is neither empty nor null string");
      }
   }
   public static void main(String[] args) {
      String input_string = null;
      System.out.println("The string is defined as: " +input_string);
      isNullEmpty(input_string);
   }
}

Output

The string is defined as: null

The string is a null string
raja
Updated on 30-Mar-2022 06:53:24

Advertisements