How to check type of variable in Java?

How to check type of variable in Java?

Java is a statically typed language, so the compiler does most of this checking for you. Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type).

The examples you gave (int, array, double) these are all primitives, and there are no sub-types of them. Thus, if you declare a variable to be an int:

int x;

You can be sure it will only ever hold int values.

If you declared a variable to be a List, however, it is possible that the variable will hold sub-types of List. Examples of these include ArrayList, LinkedList, etc.

If you did have a List variable, and you needed to know if it was an ArrayList, you could do the following:

List y;
...
if (y instanceof ArrayList) { 
  ...its and ArrayList...
}

However, if you find yourself thinking you need to do that, you may want to rethink your approach. In most cases, if you follow object-oriented principles, you will not need to do this. There are, of course, exceptions to every rule, though.

Actually quite easy to roll your own tester, by abusing Javas method overload ability. Though Im still curious if there is an official method in the sdk.

Example:

class Typetester {
    void printType(byte x) {
        System.out.println(x +  is an byte);
    }
    void printType(int x) {
        System.out.println(x +  is an int);
    }
    void printType(float x) {
        System.out.println(x +  is an float);
    }
    void printType(double x) {
        System.out.println(x +  is an double);
    }
    void printType(char x) {
        System.out.println(x +  is an char);
    }
}

then:

Typetester t = new Typetester();
t.printType( yourVariable );

How to check type of variable in Java?

a.getClass().getName() – will give you the datatype of the actual object referred to by a, but not the datatype that the variable a was originally declared as or subsequently cast to.

boolean b = a instanceof String – will give you whether or not the actual object referred to by a is an instance of a specific class.
Again, the datatype that the variable a was originally declared as or subsequently cast to has no bearing on the result of the instanceof operator.

I took this information from:
How do you know a variable type in java?

This can happen. Im trying to parse a String into an int and Id like to know if my Integer.parseInt(s.substring(a, b)) is kicking out an int or garbage before I try to sum it up.

By the way, this is known as Reflection. Heres some more information on the subject: http://docs.oracle.com/javase/tutorial/reflect/

Leave a Reply

Your email address will not be published. Required fields are marked *