How do I check if a character is a whitespace in Java?

Whitespace characters in Java (or programming in general) aren’t just the space ' ' character. It also includes other characters that create some form of space or break in the text. The most common ones include:

  • space ' '
  • tab '\t'
  • newline '\n'
  • carriage return '\r'
  • form feed '\f'.

All these characters fall into the category of whitespace characters.

Now, if we want to check if a character in Java is one of these whitespace characters, we can make use of the built-in method Character.isWhitespace(char ch). Character is a class in Java that provides a number of useful class (i.e., static) methods for working with characters. And the isWhitespace() method is one of them which checks if the provided character is a whitespace character.

Here is a simple code snippet:

package org.kodejava.lang;

public class CharacterIsWhitespace {
    public static void main(String[] args) {
        char ch = ' ';

        if (Character.isWhitespace(ch)) {
            System.out.println(ch + " is a whitespace character.");
        } else {
            System.out.println(ch + " is not a whitespace character.");
        }
    }
}

This code first defines a character ch and then uses Character.isWhitespace(ch) to check if it is a whitespace character. The isWhitespace() method returns true if the given character is a space, new line, tab, or other whitespace characters, false otherwise.

Here’s a little more expansive example:

package org.kodejava.lang;

import java.util.Arrays;
import java.util.List;

public class CharacterIsWhitespaceDemo {
    public static void main(String[] args) {
        List<Character> characters = Arrays.asList(' ', '\t', '\n', '\r', '\f', 'a', '1');
        for (char ch : characters) {
            if (Character.isWhitespace(ch)) {
                System.out.println("'" + ch + "' is a whitespace character.");
            } else {
                System.out.println("'" + ch + "' is not a whitespace character.");
            }
        }
    }
}

Output:

' ' is a whitespace character.
'   ' is a whitespace character.
'
' is a whitespace character.
' is a whitespace character.
'' is a whitespace character.
'a' is not a whitespace character.
'1' is not a whitespace character.

In this code snippet, we are checking and outputting whether each character in a list of characters is a whitespace character or not. The list includes a space, a tab, newline, carriage return, form feed, an alphabetic character, and a digit. The isWhitespace() method identifies correctly which ones are the whitespace characters.

The Character.isWhitespace(char ch) method in Java also considers Unicode whitespace. It checks for whitespace according to the Unicode standard. The method considers a character as a whitespace if and only if it is a Unicode space separator (category “Zs”), or if it is one of the following explicit characters:

  • U+0009, HORIZONTAL TABULATION (‘\t’)
  • U+000A, LINE FEED (‘\n’)
  • U+000B, VERTICAL TABULATION
  • U+000C, FORM FEED (‘\f’)
  • U+000D, CARRIAGE RETURN (‘\r’)

Here is an example of checking Unicode whitespace:

package org.kodejava.lang;

public class CharacterIsWhitespaceUnicode {
    public static void main(String[] args) {
        char ch = '\u2003';  // EM SPACE

        if (Character.isWhitespace(ch)) {
            System.out.println("Character '" + ch + "' (\\u2003) is a whitespace character.");
        } else {
            System.out.println("Character '" + ch + "' (\\u2003) is not a whitespace character.");
        }
    }
}

Output:

Character ' ' (\u2003) is a whitespace character.

In this example, \u2003 is a Unicode representation of the “EM SPACE” character, which is a type of space character in the Unicode standard. The isWhitespace() method correctly identifies it as a whitespace character.

How do I get char value of a string at a specified position?

The chartAt() method of the String class returns the char value at the specified index. An index ranges from 0 to length() - 1. If we specified an index beyond of this range a StringIndexOutOfBoundsException exception will be thrown.

These method use zero based index which means the first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing.

package org.kodejava.lang;

public class CharAtExample {
    public static void main(String[] args) {
        String[] colors = {"black", "white", "brown", "green", "yellow", "blue"};

        for (String color : colors) {
            // Get char value of a string at index number 3. We'll get the 
            // fourth character of each color in the array because the 
            // index is zero based.
            char value = color.charAt(3);
            System.out.printf("The fourth char of %s is '%s'.%n", color, value);
        }

    }
}

Here is the program output:

The fourth char of black is 'c'
The fourth char of white is 't'
The fourth char of brown is 'w'
The fourth char of green is 'e'
The fourth char of yellow is 'l'
The fourth char of blue is 'e'

How do I replace characters in string?

package org.kodejava.lang;

public class StringReplace {
    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog";
        System.out.println("Before: " + text);

        // The replace method replace all occurrences of character
        // 'o' with 'u' and returns a new string object.
        text = text.replace('o', 'u');
        System.out.println("After : " + text);
    }
}

The result of the code snippet:

Before: The quick brown fox jumps over the lazy dog
After : The quick bruwn fux jumps uver the lazy dug

How do I create a repeated sequence of character?

This example shows you how to create a repeated sequence of characters. To do this, we use the Arrays.fill() method. This method fills an array of char with a character.

package org.kodejava.util;

import java.util.Arrays;

public class RepeatCharacterExample {
    public static void main(String[] args) {
        char c = '*';
        int length = 10;

        // creates a char array with 10 elements
        char[] chars = new char[length];

        // fill each element of the char array with '*'
        Arrays.fill(chars, c);

        // print out the repeated '*'
        System.out.println(String.valueOf(chars));
    }
}

As the result you get the x character repeated 10 times.

**********

For one-liner code, you can use the following code snippet, which will give you the same result.

public class Test {
    public static void main(String[] args) {
        String str = new String(new char[10]).replace('\u0000', '*');
    }
}

Or

import java.util.Collections;

public class Test {
    public static void main(String[] args) {
        String str = String.join("", Collections.nCopies(10, "*"));
    }
}

How do I know if a character is uppercase?

In the previous example How do I know if a character is lowercase?, we’ve learned how to use the Character.isLowerCase() method. Now we will learn how to use the other method, which is the Character.isUpperCase() to determine if a letter is in an uppercase form. This method also return a boolean value that indicates whether the character is in uppercase form or not.

But first things first. Before you dive into the learning, make sure all other matters are taken care of, as learning to code will require your absolute dedication. If you are a student, you can use essay writing services to outsource some of your assignments. If you work full-time, consider taking a few days off. This way, you will get a clearer mind and more energy for studying.

Another way to check if a letter is in uppercase form is by comparing the type of the characters, that can be obtained using the Character.getType() method with a defined constant value Character.UPPERCASE_LETTER.

Below is the code snippet that demonstrate these methods.

package org.kodejava.example.lang;

public class CharacterIsUpperCaseExample {
    public static void main(String[] args) {
        char a = 'A';

        // Checks to see if a letter is a uppercase letter.
        if (Character.isUpperCase(a)) {
            System.out.println(a + " is an uppercase character.");
        }

        // Checks to see if a letter is an uppercase letter
        // by comparing the character type against
        // Character.UPPERCASE_LETTER constant value.
        int charType = Character.getType(a);
        if (charType == Character.UPPERCASE_LETTER) {
            System.out.println(a + " is an uppercase character.");
        }
    }
}

The above example give you the following result when it executed:

A is an uppercase character.
A is an uppercase character.