×

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

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.

Convert Char array to string in java

A collection of characters is referred to as a string. A character array differs from a string in that the string is canceled by the special character "\0." A string...

4 minutes read.

Java String getBytes() method

getBytes() method returns sequence of bytes. Syntax: There are three variants of getBytes() method: public byte[] getBytes()        public byte[] getBytes(String charsetName) public byte[] getBytes(Charset charset) Returns: It returns sequence of bytes. Java String getBytes() Example...

2 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

Collections in Java

Collection framework is one of Java's most powerful subsystems. It is a set of classes and interfaces that is all-the-rage technology for superintending objects and a group of objects. In...

6 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Getting Synchronized Set from Java HashSet

The synchronizedSet() technique for java.util.Collections class is utilized to return a synchronized (string safe) set supported by the predetermined set. To ensure sequential access, it is important that everything admittance...

4 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Program to Implement FLAMES Game in Java

Friends, Lovers, Affectionate, Marriage, Enemies, and Sibling are all represented by the acronym FLAMES, which also serves as the name of a well-known game. Although, it can be entertaining to...

4 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

Java Byte Keyword

Byte: The Keyword Byte in Java programming language is a primitive data type.Digital content that is most used for eight bits is called as a byte.The Java Byte Keyword is used...

3 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

Java Pass-by-Reference

In Java, passing parameters can be done using one of two fundamental methods. Pass-by-value is used for the first and pass-by-reference is used for the second. One thing to keep...

2 minutes read.

Java Break Keyword

Break: The word Break is a keyword or a statement in a java programming language.This Keyword break is used to stop the execution of the loop or switch statements etc.The loop...

3 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Java New Keyword

To create a class instance in Java, use the new keyword. In other words, it returns a reference to the memory that was allocated for a new object and instantiates...

3 minutes read.