×

How to check data type in Java

In this section, we will learn about the methodology to verify the data type in Java. There are mainly two methods in java called as getClass() and getName(). They are leveraged in order to check the data type in java.

Since, we can execute the logic operations using the identical type of variables, we occasionally need to verify the data type of such a variable before computing data. We utilize the getClass() and getSimpleName() methods to obtain the class and name of the data, respectively, in order to check the data type. We will learn about how to check the data type in Java in this article.

File name: Verifydtatatype1.java

import java.util.*;  
// To validate the variable's datatype, create the class Verifydatatype.
public class CheckDataTypeExample {  
    // this is the main method() 
    public static void main(String args[]) {  
                // declaration of variables
        int intData;  
        char charData;  
          
        //Creation of scanner class for considering the variables from the user
        Scanner s = new Scanner(System.in);  
          
        //Considering inputs from the user to initialize variables  
          
        System.out.println("Pass the string value:");  
        String str = s.nextLine();  
          
        System.out.println("Pass the integer value:");  
        intData = s.nextInt();  
          
        System.out.println("Pass the character value:");  
        charData = s.next().charAt(0);  
          
        // Closing the scanner class object
        s.close();  
          
// Displays datatypes of variables by using getClass() and getSimpleName() methods  
        System.out.println(intData + " is of type " + ((Object)intData).getClass().getSimpleName());  
        System.out.println(charData + " is of type " + ((Object)charData).getClass().getSimpleName());  
        System.out.println(str + " is of type " + str.getClass().getSimpleName());  
    }  
}  

Output

Pass the string value:
Arya
Pass the integer value:
143
Pass the character value:
r
143 is of type Integer
r is of type Character
Arya is of type String

We now have a unique method, getType(), which is made available by the java.lang.reflect.Field as well as Character classes. Let's examine each class's getType() method individually.

To determine the type of field that the Field object defines, use the getType() function of the Field class. We can identify the type of variable by looking at the return value.

To get the broad category of a given character, utilize the getType() function of the Character class. Two variations of the getType() method are available depending on the parameter, which is a character. Character and getType(char ch). getType(int codePoint) (int codePoint).

Supplementary characters cannot be handled by the getType() function that accepts a char as a parameter; however, they can be handled by the getType() method which accepts an int as a parameter.

File name: Verifydatatype2.java

import java.lang.reflect.Field;  
   
//To get the type of data type of variable, the class is created 
public class Verifydatatype2 {  
   
    public static void main(String[] args)throws Exception  
        {  
    
    
                Field nameField = Engineer.class.getField("name");  
    
                // using getType() method of the variable to the type of the data  
                Class value = nameField.getType();  
    
                //displaying the type of data type
                System.out.println("The type of the name field is " + value);  
    
                //get the totalDays field object by using getField() method  
                Field daysField = Engineer.class.getField("totalDays");  
    
                // use getTyoe() method of the Field to get the type of totalDays field  
                value = daysField.getType();  
    
                // print the type of name field  
                System.out.println("The type of the totalDays field is " + value);  
  
        //get the totalSalary field object by using getField() method  
                Field salaryField = Engineer.class.getField("totalSalary");  
    
                // use getTyoe() method of the Field to get the type of name field  
                value = salaryField.getType();  
    
                // print the type of the totalSalary field  
                System.out.println("The type of the totalSalary field is " + value);  
        }  
}  
    
// create a simple Engineer class  
class Engineer {  
    
        // declrartion and initialization of the variables 
        public static String name = "John";  
    public static double totalDays = 300;  
         public static float totalSalary = 3413.99f;  
    
        // getter for Engineer name  
    public static String getName()  
        {  
                return name;  
        }  
  
    // setter for Engineer name  
        public static void setName(String stdName)  
        {  
                name = stdName;  
        }  
  
// getter for totalDays  
    public static double getTotalDays()  
        {  
                return totalDays;  
        }     
  
// setter for totalDays  
        public static void setDays(double days)  
        {  
                totalDays = days;  
        }  
  
// getter for totalSalary  
    public static float getTotalSalary()  
        {  
                return totalSalary;  
        }  
  
    // setter for totalSalary  
    public static void setSalary(float salary)  
        {  
                totalSalary = salary;  
        }     
}  

Output

The type of the name field is class java.lang.String
The type of the totalDays field is double
The type of the totalSalary field is float

Related Topics

Packages in Java

Packages in Java can be defined as an assortment for grouping various classes and interfaces based on their performance. It is a catalog for holding various java files. They provide...

4 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.

Parallel Arrays Sort in Java

Sorting is a technique of arranging a sequence of numbers in ascending order, that is, the first number being lowest and gradually incrementing the numbers such that the last number...

7 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

Maximum length of string in java

In java, String can act as a data type and a class. The string can be defined as the collection of characters that are enclosed with double quotes(“ “). The...

3 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.

Java Integer toOctalString() method

The toOctalString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 8. Syntax public static String toOctalString (int  i) Parameters The parameter ‘i’ represents...

1 minute read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date. In order to get the date of birth from the current...

6 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Application of Array in Java

In this article we are going to acknowledge about what the array is, types of arrays and their applications. What is an array? An array is often a set of interrelated elements...

4 minutes read.

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.