Javatpoint Logo
Javatpoint Logo

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.

CheckDataTypeExample.java

Output:

How to check data type in Java

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.

Field.getType()

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.

Syntax:

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:

GetTypeExample1.java

Output:

How to check data type in Java

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.

Syntax:

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:

GetTypeExample2.java

Output:

How to check data type in Java

GetTypeExample3.java

Output:

How to check data type in Java
Next TopicJava Array Clone





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA