0

I am trying to know how to tell if two variables share the same primitive data type in Java. Let's say there's a method compareType() that would return true if two variables do share the same primitive data type; false otherwise.

For example,

int i = 1;
int i1 = 2;
long l = 1;
float f = 0.1f;
double d = 0.1d;

Then, compareType(f,d) will return false; compareType(i,l) will return false; compareType(i,i1) will return true;

I know in Python there is the function type() which will return something like "int", and the key component for compareType() is a function in Java that works like type() in Python. That is what I am searching for.

1 Answers1

3
static boolean compareType(Object a, Object b) {
    return a.getClass().equals(b.getClass));
}

The primatives will be coerced into their object counterparts. So Integer and ints will return true if compared.

That being said, I can't imagine a good reason to have this method.

der_Fidelis
  • 1,475
  • 1
  • 11
  • 25
  • Thank you for the reply! I tried the getClass(), but the java compiler would give (error: int cannot be dereferenced). I am having this problem of finding the primitive data type of a variable because I am designing a test for building a class that includes the method toDouble(), toInt(), toFloat(),etc, and I want to verify that the converted results are as desired. – Henry Li-Heng Chang Sep 16 '18 at 01:08
  • You could check the return type of the _method_ toDouble, but it doesn't make sense to test the type of a primitive value. – Louis Wasserman Sep 16 '18 at 02:06
  • So @Louis Wasserman, you mean that you can only check a variable's primitive type from the implementation and never from the interface? – Henry Li-Heng Chang Sep 16 '18 at 14:42
  • There _isn't_ an interface for primitive types. – Louis Wasserman Sep 16 '18 at 18:41