Finding the type of variable, knowing it's a primitive datatype

Viewed 70

I read this post here that allows us to tell us what data type the object entails. Is there a way to do that with primitive data types? Does that mean I would have to autbox the variable then apply some method to it? For instance:

float d1 = 10;
float d2 = 10.1f;
double d3 = d1 + d2;

Is there a way for me to print d3's data type?

TIA

1 Answers

You can have a helper method in order to perform boxing, and use getClass()

public static <T> Class<?> typeOf(final T value) { 
  return value.getClass(); 
}
jshell> double x = 10.0;
x ==> 10.0
jshell> float y = 10.0f;
y ==> 10.0
jshell> typeOf(y)
$4 ==> class java.lang.Float
jshell> typeOf(x)
$5 ==> class java.lang.Double
Related