How to Check If a Character Is Whitespace in Java

JavaJavaBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a character is whitespace in Java using the Character.isWhitespace() method. You will explore how this method identifies various whitespace characters, including spaces, tabs, newlines, and carriage returns.

Through hands-on exercises, you will test the method with different characters, including spaces, tabs, and non-whitespace characters like letters and digits, to understand its behavior and practical application in Java programming.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("Java")) -.-> java/BasicSyntaxGroup(["Basic Syntax"]) java(("Java")) -.-> java/StringManipulationGroup(["String Manipulation"]) java(("Java")) -.-> java/SystemandDataProcessingGroup(["System and Data Processing"]) java/BasicSyntaxGroup -.-> java/data_types("Data Types") java/BasicSyntaxGroup -.-> java/operators("Operators") java/BasicSyntaxGroup -.-> java/for_loop("For Loop") java/StringManipulationGroup -.-> java/strings("Strings") java/SystemandDataProcessingGroup -.-> java/object_methods("Object Methods") subgraph Lab Skills java/data_types -.-> lab-559939{{"How to Check If a Character Is Whitespace in Java"}} java/operators -.-> lab-559939{{"How to Check If a Character Is Whitespace in Java"}} java/for_loop -.-> lab-559939{{"How to Check If a Character Is Whitespace in Java"}} java/strings -.-> lab-559939{{"How to Check If a Character Is Whitespace in Java"}} java/object_methods -.-> lab-559939{{"How to Check If a Character Is Whitespace in Java"}} end

Use Character.isWhitespace() Method

In this step, we will explore how to use the Character.isWhitespace() method in Java. This method is part of the Character class and is used to determine if a given character is a whitespace character. Whitespace characters include spaces, tabs, newlines, and carriage returns.

Understanding how to identify whitespace is useful in many programming tasks, such as parsing text, validating input, or formatting output.

Let's create a new Java file to experiment with this method.

  1. Open the WebIDE if it's not already open.

  2. In the File Explorer on the left, make sure you are in the ~/project directory.

  3. Right-click in the empty space within the ~/project directory and select "New File".

  4. Name the new file WhitespaceChecker.java.

  5. Open the WhitespaceChecker.java file in the editor.

  6. Copy and paste the following Java code into the editor:

    public class WhitespaceChecker {
        public static void main(String[] args) {
            char space = ' ';
            char tab = '\t';
            char newline = '\n';
            char letter = 'a';
            char digit = '1';
    
            System.out.println("Is '" + space + "' whitespace? " + Character.isWhitespace(space));
            System.out.println("Is '" + tab + "' whitespace? " + Character.isWhitespace(tab));
            System.out.println("Is '" + newline + "' whitespace? " + Character.isWhitespace(newline));
            System.out.println("Is '" + letter + "' whitespace? " + Character.isWhitespace(letter));
            System.out.println("Is '" + digit + "' whitespace? " + Character.isWhitespace(digit));
        }
    }

    Let's look at the new parts of this code:

    • char space = ' ';: This declares a variable named space of type char and assigns it the space character.
    • char tab = '\t';: This declares a variable named tab and assigns it the tab character. \t is an escape sequence representing a tab.
    • char newline = '\n';: This declares a variable named newline and assigns it the newline character. \n is an escape sequence representing a newline.
    • char letter = 'a';: This declares a variable named letter and assigns it the character 'a'.
    • char digit = '1';: This declares a variable named digit and assigns it the character '1'.
    • Character.isWhitespace(space): This is where we call the isWhitespace() method. We pass the space character to it, and it will return true if the character is whitespace, and false otherwise. We do the same for the other characters.
    • System.out.println(...): We use println to print the result of the isWhitespace() method call along with a descriptive message.
  7. Save the WhitespaceChecker.java file (Ctrl+S or Cmd+S).

Now that we have written the code, we need to compile and run it to see the output.

  1. Open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.

  2. Compile the Java program using the javac command:

    javac WhitespaceChecker.java

    If there are no errors, this command will create a WhitespaceChecker.class file in the ~/project directory.

  3. Run the compiled Java program using the java command:

    java WhitespaceChecker

    You should see output similar to this:

    Is ' ' whitespace? true
    Is '	' whitespace? true
    Is '
    ' whitespace? true
    Is 'a' whitespace? false
    Is '1' whitespace? false

    This output shows that the isWhitespace() method correctly identified the space, tab, and newline characters as whitespace, and the letter and digit characters as non-whitespace.

You have successfully used the Character.isWhitespace() method to check different characters. In the next step, we will test this method with more examples, including different types of whitespace.

Test with Spaces and Tabs

In the previous step, we used Character.isWhitespace() with a single space and a single tab character. In this step, we will further test the method with strings containing multiple spaces and tabs to see how it behaves.

Remember that Character.isWhitespace() works on individual characters, not entire strings. To check if a string contains only whitespace, or to process whitespace within a string, you would typically iterate through the string character by character and apply the isWhitespace() method to each one.

Let's modify our WhitespaceChecker.java file to include tests with multiple spaces and tabs.

  1. Open the WhitespaceChecker.java file in the WebIDE editor.

  2. Replace the existing code with the following updated code:

    public class WhitespaceChecker {
        public static void main(String[] args) {
            char space = ' ';
            char tab = '\t';
            char newline = '\n';
            char letter = 'a';
            char digit = '1';
    
            System.out.println("Is '" + space + "' whitespace? " + Character.isWhitespace(space));
            System.out.println("Is '" + tab + "' whitespace? " + Character.isWhitespace(tab));
            System.out.println("Is '" + newline + "' whitespace? " + Character.isWhitespace(newline));
            System.out.println("Is '" + letter + "' whitespace? " + Character.isWhitespace(letter));
            System.out.println("Is '" + digit + "' whitespace? " + Character.isWhitespace(digit));
    
            System.out.println("\nTesting with multiple characters:");
    
            String testString1 = "   "; // Three spaces
            String testString2 = "\t\t"; // Two tabs
            String testString3 = "  \t  "; // Spaces and tabs
            String testString4 = "Hello World"; // Contains space, but also letters
    
            System.out.println("Checking characters in: \"" + testString1 + "\"");
            for (int i = 0; i < testString1.length(); i++) {
                char c = testString1.charAt(i);
                System.out.println("  Is '" + (c == ' ' ? " " : (c == '\t' ? "\\t" : c)) + "' whitespace? " + Character.isWhitespace(c));
            }
    
            System.out.println("Checking characters in: \"" + testString2 + "\"");
            for (int i = 0; i < testString2.length(); i++) {
                char c = testString2.charAt(i);
                 System.out.println("  Is '" + (c == ' ' ? " " : (c == '\t' ? "\\t" : c)) + "' whitespace? " + Character.isWhitespace(c));
            }
    
            System.out.println("Checking characters in: \"" + testString3 + "\"");
            for (int i = 0; i < testString3.length(); i++) {
                char c = testString3.charAt(i);
                 System.out.println("  Is '" + (c == ' ' ? " " : (c == '\t' ? "\\t" : c)) + "' whitespace? " + Character.isWhitespace(c));
            }
    
             System.out.println("Checking characters in: \"" + testString4 + "\"");
            for (int i = 0; i < testString4.length(); i++) {
                char c = testString4.charAt(i);
                 System.out.println("  Is '" + (c == ' ' ? " " : (c == '\t' ? "\\t" : c)) + "' whitespace? " + Character.isWhitespace(c));
            }
        }
    }

    Here's a breakdown of the new code:

    • String testString1 = " ";: We create a string with three space characters.
    • String testString2 = "\t\t";: We create a string with two tab characters.
    • String testString3 = " \t ";: We create a string with a mix of spaces and tabs.
    • String testString4 = "Hello World";: We create a string with letters and a space.
    • for (int i = 0; i < testString1.length(); i++): This is a for loop that iterates through each character of the string.
    • char c = testString1.charAt(i);: Inside the loop, charAt(i) gets the character at the current index i and stores it in the c variable.
    • System.out.println(" Is '" + (c == ' ' ? " " : (c == '\t' ? "\\t" : c)) + "' whitespace? " + Character.isWhitespace(c));: This line prints whether the current character c is whitespace using Character.isWhitespace(c). The part (c == ' ' ? " " : (c == '\t' ? "\\t" : c)) is a ternary operator used to print a visible representation for space and tab characters in the output.
  3. Save the WhitespaceChecker.java file.

Now, let's compile and run the updated program.

  1. Open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.

  2. Compile the Java program:

    javac WhitespaceChecker.java
  3. Run the compiled Java program:

    java WhitespaceChecker

    You should see output similar to this, including the results for each character in the test strings:

    Is ' ' whitespace? true
    Is '	' whitespace? true
    Is '
    ' whitespace? true
    Is 'a' whitespace? false
    Is '1' whitespace? false
    
    Testing with multiple characters:
    Checking characters in: "   "
      Is ' ' whitespace? true
      Is ' ' whitespace? true
      Is ' ' whitespace? true
    Checking characters in: "		"
      Is '\t' whitespace? true
      Is '\t' whitespace? true
    Checking characters in: "  	  "
      Is ' ' whitespace? true
      Is ' ' whitespace? true
      Is '\t' whitespace? true
      Is ' ' whitespace? true
      Is ' ' whitespace? true
    Checking characters in: "Hello World"
      Is 'H' whitespace? false
      Is 'e' whitespace? false
      Is 'l' whitespace? false
      Is 'l' whitespace? false
      Is 'o' whitespace? false
      Is ' ' whitespace? true
      Is 'W' whitespace? false
      Is 'o' whitespace? false
      Is 'r' whitespace? false
      Is 'l' whitespace? false
      Is 'd' whitespace? false

    This output confirms that Character.isWhitespace() correctly identifies individual space and tab characters within strings, even when they appear consecutively or mixed with other characters.

You have successfully tested Character.isWhitespace() with strings containing multiple spaces and tabs by iterating through the characters. In the next step, we will look at how the method handles non-whitespace characters.

Handle Non-Whitespace Characters

In the previous steps, we focused on identifying whitespace characters using Character.isWhitespace(). Now, let's explicitly demonstrate how the method handles characters that are not considered whitespace. This will reinforce your understanding of what the method does and doesn't identify.

While we already included some non-whitespace characters in the previous examples (like 'a' and '1'), let's add a few more diverse examples to our WhitespaceChecker.java file.

  1. Open the WhitespaceChecker.java file in the WebIDE editor.

  2. Add the following lines of code within the main method, after the existing System.out.println statements but before the loops that iterate through strings. You can add them after the line System.out.println("Is '" + digit + "' whitespace? " + Character.isWhitespace(digit));.

            char punctuation = '.';
            char symbol = '$';
            char controlChar = '\u0000'; // Null character
    
            System.out.println("Is '" + punctuation + "' whitespace? " + Character.isWhitespace(punctuation));
            System.out.println("Is '" + symbol + "' whitespace? " + Character.isWhitespace(symbol));
            System.out.println("Is U+0000 whitespace? " + Character.isWhitespace(controlChar)); // Printing control chars might not display correctly

    Let's look at the new characters we've added:

    • char punctuation = '.';: A punctuation mark.
    • char symbol = '$';: A symbol character.
    • char controlChar = '\u0000';: This is a Unicode escape sequence for the null character, which is a control character. Character.isWhitespace() also checks for certain control characters that are considered whitespace by the Unicode standard.
  3. Save the WhitespaceChecker.java file.

Now, let's compile and run the updated program to see the output for these new characters.

  1. Open the Terminal at the bottom of the WebIDE. Make sure you are in the ~/project directory.

  2. Compile the Java program:

    javac WhitespaceChecker.java
  3. Run the compiled Java program:

    java WhitespaceChecker

    You should see output similar to this, including the results for the new characters:

    Is ' ' whitespace? true
    Is '	' whitespace? true
    Is '
    ' whitespace? true
    Is 'a' whitespace? false
    Is '1' whitespace? false
    Is '.' whitespace? false
    Is '$' whitespace? false
    Is U+0000 whitespace? false
    
    Testing with multiple characters:
    Checking characters in: "   "
      Is ' ' whitespace? true
      Is ' ' whitespace? true
      Is ' ' whitespace? true
    Checking characters in: "		"
      Is '\t' whitespace? true
      Is '\t' whitespace? true
    Checking characters in: "  	  "
      Is ' ' whitespace? true
      Is ' ' whitespace? true
      Is '\t' whitespace? true
      Is ' ' whitespace? true
      Is ' ' whitespace? true
    Checking characters in: "Hello World"
      Is 'H' whitespace? false
      Is 'e' whitespace? false
      Is 'l' whitespace? false
      Is 'l' whitespace? false
      Is 'o' whitespace? false
      Is ' ' whitespace? true
      Is 'W' whitespace? false
      Is 'o' whitespace? false
      Is 'r' whitespace? false
      Is 'l' whitespace? false
      Is 'd' whitespace? false

    As you can see from the output, the punctuation mark ('.') and the symbol ('$') are correctly identified as non-whitespace. The null character (\u0000) is also identified as non-whitespace by Character.isWhitespace(). This method specifically checks for characters defined as whitespace in the Unicode standard, which includes space, tab, newline, carriage return, form feed (\f), and certain other control characters and space separators.

You have now seen how Character.isWhitespace() behaves with various types of characters, including standard whitespace and non-whitespace characters like punctuation, symbols, and control characters. This completes our exploration of the Character.isWhitespace() method.

Summary

In this lab, we learned how to check if a character is whitespace in Java using the Character.isWhitespace() method. We explored how this method identifies common whitespace characters like spaces, tabs, and newlines.

We practiced using the Character.isWhitespace() method by creating a simple Java program that tested various characters, including spaces, tabs, and non-whitespace characters like letters and digits, to see if they were classified as whitespace. This hands-on exercise demonstrated the practical application of the method for identifying and handling whitespace in Java code.