Demonstrating the isSpaceChar(char ch)
method
Let's implement a Java program that demonstrates the usage of the isSpaceChar(char ch)
method using user-defined examples. Copy the following code to your SpaceCharDemo.java
file:
import java.util.Scanner;
public class SpaceCharDemo {
public static void main(String[] args) {
// Example 1
char ch1 = 'h';
char ch2 = '\u2028';
char ch3 = '\u2078';
char ch4 = '0';
char ch5 = ' ';
boolean b1 = Character.isSpaceChar(ch1);
boolean b2 = Character.isSpaceChar(ch2);
boolean b3 = Character.isSpaceChar(ch3);
boolean b4 = Character.isSpaceChar(ch4);
boolean b5 = Character.isSpaceChar(ch5);
System.out.println(ch1 + " is a space character? " + b1);
System.out.println(ch2 + " is a space character? " + b2);
System.out.println(ch3 + " is a space character? " + b3);
System.out.println(ch4 + " is a space character? " + b4);
System.out.println(ch5 + " is a space character? " + b5);
// Example 2
try {
System.out.print("Enter a character: ");
Scanner sc = new Scanner(System.in);
char ch = sc.next().charAt(0);
boolean b = Character.isSpaceChar(ch);
System.out.println(ch + " is a space character? " + b);
} catch (Exception e) {
System.out.println("Invalid Input!!");
}
}
}
In the above code, we have demonstrated the usage of the isSpaceChar(char ch)
method using two examples.
In the first example, we have declared five characters of different types and using the isSpaceChar(char ch)
method, we have identified whether the given characters are Unicode space characters or not. In the second example, we have taken input from the user and used the isSpaceChar(char ch)
method to identify whether the given character is a space character or not.
Note that in the second example, we are using the Scanner
class to take input from the user.