Program to check if the String is Null in Java

Given a string str, the task is to check if this string is null or not, in Java.

Examples:

Input: str = null 
Output: True

Input: str = "GFG"
Output: False

Approach:

  • Get the String to be checked in str
  • We can simply compare the string with Null using == relational operator.
    Syntax:

    if(str == null)
    
  • Print true if the above condition is true. Else print false.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to check if
// the String is Null in Java
  
class GFG {
  
    // Function to check if the String is Null
    public static boolean isStringNull(String str)
    {
  
        // Compare the string with null
        // using == relational operator
        // and return the result
        if (str == null)
            return true;
        else
            return false;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str1 = "GeeksforGeeks";
        String str2 = null;
  
        System.out.println("Is string [" + str1
                           + "] null? "
                           + isStringNull(str1));
        System.out.println("Is string [" + str2
                           + "] null? "
                           + isStringNull(str2));
    }
}

chevron_right


Output:

Is string [GeeksforGeeks] null? false
Is string [null] null? true

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.