How to check data type in Java?
Sometimes, we need to check the data type of a variable to compute data because we can perform the logical operation with the same type of variables. In order to check the data type, we use getClass() and getSimpleName() method to get class and its name respectively. In this section, we will discuss how to check data type in Java?
Let's implement the code for getting data types of the variables. We first take input from the user, and then we find the data type of the variables in which user input will be stored.
Now, we have a special method, i.e., getType() provided by java.lang.reflect.Field and Character classes. Let's understand the getType() method of both classes one by one.
The getType() method of the Field class is used to get the type of field defined by the Field object. The return value helps us in identifying the type of the field.
The syntax of the getType() method is as follows:
Parameter: It accepts no argument as a parameter.
Returns: It returns a class object that helps us in identifying the type of the field.
Let's take an example of the getType() method and understand how it works:
Using Field.getType() Method
The getType() method of Character class is used to get general category of the given character. The getType() method comes with two variation based on the parameter, I.e., Character.getType(char ch) and Character.getType(int codePoint).
The getType() method that takes char as a parameter cannot handle the supplementary characters, whereas the getType() method that takes an int as a parameter can handle supplementary characters.
The getType() method of the Character class has the following syntax:
Parameter: The first variation of the getType() method accepts a parameter of type char and the second variation of the method accepts a parameter of type int, i.e., codePoint.
Returns: Both the methods return an integer value that indicates the general category of character.
Let's take an example of getType() method and understand how it works:
Next TopicJava Array Clone