×

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

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Diffie Hellman Algorithm in Java

In this section, you will be acknowledged about Diffie Hellman algorithm clearly step wise along with an example and also an example program. Diffie Hellman Algorithm One of the most significant algorithms...

3 minutes read.

StringBuffer in Java

StringBuffer in Java Similar to StringBuilder, the Java StringBuffer class is also used to create modifiable or mutable strings. The StringBuilder class is synchronized, i.e., thread-safe. Java StringBuffer ConstructorThe StringBuffer class has...

7 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 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.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Prime Number Program in Java

Prime Number Program in Java using for loop A natural number which is greater than 1 and has only two factors the number itself and 1 is called prime number. In...

2 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.

Zebra Puzzle Problem in Java

Complex puzzles like the zebra puzzle demand a lot of work and mental training to complete. Because it was created by renowned German scientist Albert Einstein, it is also sometimes...

10 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

Order of Execution of Constructors in Java Inheritance

Constructor in Java There are several distinctions between a method and a function object() in Java. The name of the function object()  is identical to the class name. There is no...

4 minutes read.