Program to check if a String in Java contains only whitespaces

Given a string str, the task is to check if this string contains only whitespaces or some text, in Java.

Examples:

Input: str = "              " 
Output: True

Input: str = "GFG"
Output: False

Approach:

  • Get the String to be checked in str
  • We can use the trim() method of String class to remove the leading whitespaces in the string.
    Syntax:

    str.trim()
    
  • Then we can use the isEmpty() method of String class to check if the resultant string is empty or not. If the string contained only whitespaces, then this method will return true
    Syntax:



    str.isEmpty()
    
  • Combine the use of both methods using Method Chaining.
    str.trim().isEmpty();
    
  • 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 not all whitespaces
  
class GFG {
  
    // Function to check if the String is all whitespaces
    public static boolean isStringAllWhiteSpace(String str)
    {
  
        // Remove the leading whitespaces using trim()
        // and then check if this string is empty
        if (str.trim().isEmpty())
            return true;
        else
            return false;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str1 = "GeeksforGeeks";
        String str2 = "              ";
  
        System.out.println("Is string [" + str1
                           + "] only whitespaces? "
                           + isStringAllWhiteSpace(str1));
        System.out.println("Is string [" + str2
                           + "] only whitespaces? "
                           + isStringAllWhiteSpace(str2));
    }
}

chevron_right


Output:

Is string [GeeksforGeeks] only whitespaces? false
Is string [              ] only whitespaces? 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 :


5


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