QuizCure
Find Available Solution Here!

Java Get type of Variable

Deepak Dec 21, 2024

A variable's type should be specified once it's been declared in Java programming. Whether the variable is an Integer, Sting, or any other dataType, for example. While compiling Java source code, the compiler determined the type of specified variable and verified it. Variable type checks are performed at compile time rather than during execution in Java because it is a statically typed language.

However, there are times when we don't know the type of variables, such as user input values, which could be an integer, a String, or another data type. In such circumstances, we may require checking type in java before continuing to handle user input data.

Let's look at a few different type-checking scenarios with simple samples.

How to get type of variable in Java with the full package name?

In the previous section, it's explained the getSimpleName() method which returns the underlying class name without the package but if we need to find the name of the class name of the variable with the full package then we have to use the getName() method.

Please review the example code below for a demonstration

package javaapplication;

public class GetNameDemo {

    public static void main(String args[]) {

        Object[] mixedObjects = new Object[]{"Hello", true, 1, new StringBuilder("Hello there"), new GetNameDemo(), new String[10]};

        for (Object item : mixedObjects) {
            System.out.println(item.getClass().getName());
        }

    }
}

Result

java.lang.String
java.lang.Boolean
java.lang.Integer
java.lang.StringBuilder
javaapplication.GetNameDemo
[Ljava.lang.String;


In Java, how do you check the type of variables without the package?

The getClass() and getSimpleName() methods can be used to determine the data type of a variable. This is one of the most used approaches for determining the type of variable.

Please note here that the method getSimpleName() will return the simple name of the underlying class without the package.

getClass retrieves the related object's runtime class, while getSimpleName returns the class's Simple name for a given object.

Consider the following code as an example:

package javaapplication;

public class Employee {

    public static void main(String args[]) {

       
        Object[] mixedObjects = new Object[]{"Hello", true, 1, new StringBuilder("Hello there"), new Employee(), new String[10]};

        for (Object item : mixedObjects) {
            System.out.println(item.getClass().getSimpleName());
        }

    }
}

Result:

String
Boolean
Integer
StringBuilder
Employee
String[]

Code Explanation:

  • We've created a mixed object array of String, Integer, Boolean, Employee Class, and String array for demonstration purposes.
  • Looping through each mixedObjects element to determine its type.
  • Using item, determine the type of each iterative element.
  • We can see that for each item in the mixedObjects array, getSimpleName returns the corresponding class name.

How can I use the isInstance method in Java to validate the data type of an object?

The method isInstance helps in the detection of the desired data type. If we are unsure about the type of a variable, we can use the isInstance method to examine what type of object.

We declare some params types as per business logic while developing a program, but some params are dynamically assessed (such as user input) and must be decided on its type before proceeding. During runtime, we must check the type of value.

With the following example, we'll learn how to use the isInstance method.

package javaapplication;

public class Employee {

    public static void main(String args[]) {

        Object[] mixedObjects = new Object[]{"Hello", true, 1, new StringBuilder("Hello there"), new Employee(), new String[10]};

        for (Object obj : mixedObjects) {

            if (String.class.isInstance(obj)) {
                System.out.println(obj + ": is String data type");
            }

            if (Integer.class.isInstance(obj)) {
                System.out.println(obj + ": is Integer data type");
            }

            if (Boolean.class.isInstance(obj)) {
                System.out.println(obj + ": is Boolean data type");
            }

            if (Employee.class.isInstance(obj)) {
                System.out.println(obj + ": is Employee data type");
            }

            if (StringBuilder.class.isInstance(obj)) {
                System.out.println(obj + ": is StringBuilder data type");
            }

            if (String[].class.isInstance(obj)) {
                System.out.println(obj + ": is  Array of string ");
            }

        }

    }
}

Result:

Hello: is String data type

true: is Boolean data type

1: is Integer data type

Hello there: is StringBuilder data type

javaapplication.Employee@6ff3c5b5: is Employee data type

[Ljava.lang.String;@3764951d: is  Array of string 

Code Explanation:

  • Created Employee class and defined an array of mixed objects for demonstration purposes.
  • Loop through the list of objects and check type with the help of isInstance method.
  • If the obj is of type String, String.class.isInstance(obj) returns true.
  • If the obj is of type Integer, Integer.class.isInstance(obj) returns true.
  • If the obj is of type Boolean, Boolean.class.isInstance(obj) returns true.
  • If the obj is of type StringBuilder, StringBuilder.class.isInstance(obj)) returns true.
  • String[].class.isInstance(obj) returns true if the obj is of type String Array.

As a result, we can build business logic according to our needs, avoiding any runtime problems for unknown type cases.

Was this post helpful?

Send Feedback

Connect With QuizCure


Follow Us and Stay tuned with upcoming blog posts and updates.

Contributed By

Deepak

Deepak

QC STAFF
51 Posts
  • PHP
  • JAVA
  • PYTHON
  • MYSQL
  • SEO

You May Like to Read

Scroll up