Java Character isWhitespace() example

In this guide, you will learn about the Character isWhitespace() method in Java programming and how to use it with an example.

1. Character isWhitespace() Method Overview

Definition:

The isWhitespace() method of the Java Character class determines if the specified character (given as a char or an int code point) is white space according to Java. This is based on characters considered whitespace in a Java-written program.

Syntax:

1. static boolean isWhitespace(char ch) 
2. static boolean isWhitespace(int codePoint)

Parameters:

char ch: The character to be tested.

int codePoint: The character (Unicode code point) to be tested.

Key Points:

- The method checks if a character is a Java whitespace character, which includes space (' '), tab ('\t'), form feed ('\f'), line feed ('\n'), or carriage return ('\r').

- It does not consider non-breaking space as a whitespace.

- The method returns true if the character is a whitespace, and false otherwise.

- For a wider Unicode set of whitespace characters, one might use Character.isSpaceChar().

2. Character isWhitespace() Method Example

public class IsWhitespaceExample {
    public static void main(String[] args) {
        char testChar1 = ' ';
        char testChar2 = 'A';
        int testCodePoint = 0x2003;  // Em space

        System.out.println("Is '" + testChar1 + "' whitespace? " + Character.isWhitespace(testChar1));
        System.out.println("Is '" + testChar2 + "' whitespace? " + Character.isWhitespace(testChar2));
        System.out.println("Is Em space represented by code point " + testCodePoint + " whitespace? " + Character.isWhitespace(testCodePoint));
    }
}

Output:

Is ' ' whitespace? true
Is 'A' whitespace? false
Is Em space represented by code point 8195 whitespace? false

Explanation:

In the example, the isWhitespace() method is tested on a space character, a Latin letter 'A', and an Em space. The method correctly identifies the space character as whitespace, returning true. However, for the letter 'A' and the Em space, it returns false as they are not considered whitespace in Java.

Comments