Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Program to check if a String in Java contains only whitespaces

  • Difficulty Level : Easy
  • Last Updated : 22 Jan, 2020

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


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: str = "              " 
Output: True

Input: str = "GFG"
Output: False


  • 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.
  • 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
  • Combine the use of both methods using Method Chaining.
  • Print true if the above condition is true. Else print false.

Below is the implementation of the above approach:

// 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;
            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));
Is string [GeeksforGeeks] only whitespaces? false
Is string [              ] only whitespaces? true

My Personal Notes arrow_drop_up
Recommended Articles
Page :