Determining Space Characters in Java

JavaJavaBeginner
Practice Now

Introduction

The isspacechar() method of the Character class in Java is used to determine whether the given character is a space character or not. It checks if the character belongs to the U+0020 'SPACE', U+0085 'NEXT LINE', U+000D 'CARRIAGE RETURN', U+000A 'LINE FEED', U+0009 'CHARACTER TABULATION' or U+000B 'LINE TABULATION' space character groups.

Create the main method

In Java, the main method is the entry point of the program. All Java programs start executing from the main method.

Create the main method with the following code:

public static void main(String[] args) {

}

Initialize a string with a value

Create a string object named text and assign it a value of "Hello World!" using the following code:

String text = "Hello World!";

Check if the string contains space characters

Use the isspacechar() method in Character class to check if the string contains any space characters.

for (int i = 0; i < text.length(); i++) {
  boolean isSpaceChar = Character.isSpaceChar(text.charAt(i));
  if (isSpaceChar) {
    System.out.println("Space character found!");
    break;
  }
}

The for loop iterates over all the characters in the string text. The Charater.isSpaceChar() method checks if the current character is a space character or not. If true, the loop is terminated and a message "Space character found!" is displayed in the console.

Test the code

Compile the code using the following command:

javac CharacterSpace.java

Execute the code using the following command:

java CharacterSpace

The output should be:

Space character found!

This means that the code has successfully detected a space character in the text string.

Summary

In this lab, you learned how to use the isspacechar() method of the Character class to determine if a given character is a space character or not. You also learned how to use a for loop to iterate over a string and check all characters in the string for space characters.

Other Java Tutorials you may like