Introduction
In this lab, we will learn about Java isDigit(char ch)
method, which is a part of Character
class. This method checks whether the specified character is a digit or not.
In this lab, we will learn about Java isDigit(char ch)
method, which is a part of Character
class. This method checks whether the specified character is a digit or not.
Firstly, we need to create a Java file in the ~/project
directory. You can use any text editor such as nano, vi editor, or simply use an IDE such as Eclipse, NetBeans, IntelliJ, etc.
Name the file IsDigitExample.java
. You can use the following command to create a file using the terminal:
touch ~/project/IsDigitExample.java
Define the class IsDigitExample
.
public class IsDigitExample {
Define the main
method inside the IsDigitExample
class. This method executes the code and creates objects.
public static void main(String[] args) {
Use the isDigit(char ch)
method of the Character
class to check whether the specified character is a digit or not. If the passed character is a digit, then this method returns true
, otherwise, it returns false
.
char ch1 = 'A';
char ch2 = 'u';
char ch3 = '8';
boolean b1 = Character.isDigit(ch1);
boolean b2 = Character.isDigit(ch2);
boolean b3 = Character.isDigit(ch3);
System.out.println(ch1 + " is a digit??: " + b1);
System.out.println(ch2 + " is a digit??: " + b2);
System.out.println(ch3 + " is a digit??: " + b3);
After writing the Java code, compile the code with the following command:
javac IsDigitExample.java
After compiling the Java code, run the program with the following command:
java IsDigitExample
Create a new method named userDefinedExample()
inside the IsDigitExample
class.
public static void userDefinedExample() {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the character: ");
char ch = scanner.next().charAt(0);
boolean result = Character.isDigit(ch);
System.out.println(ch + " is a digit?? : " + result);
} catch (Exception e) {
System.out.println("Invalid Input!!");
}
}
Invoke the userDefinedExample()
method in the main()
method.
System.out.println("Execution character digit check example:");
characterDigitCheck();
System.out.println("\nUser Defined Example:");
userDefinedExample();
Compile and run the program again with the same commands as in steps 5 and 6.
javac IsDigitExample.java
java IsDigitExample
In this lab, we learned how to check whether a specified character is a digit or not using the Java isDigit(char ch)
method. We also learned how to create a user-defined example, take input from the user and verify the output. This method is helpful when we need to validate certain types of user input.