2

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

abhivemp
  • 932
  • 6
  • 24
  • Don't you know it? `System.out.println("double")`? – Sweeper Jul 09 '20 at 02:33
  • I probably should clarify my question. I know it's a double. But I was thinking if there was something for Java to tell me that it's a double – abhivemp Jul 09 '20 at 02:36
  • Why would that be any useful? `getClass` shown in your linked question is useful because the programmer doesn't know the type of object that is passed to `printVariableType`. But here you know 100% that `d3` is `double`... You can get the `Class` of `double` using `double.class`, but that's it. – Sweeper Jul 09 '20 at 02:41

1 Answers1

3

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
andreoss
  • 1,570
  • 1
  • 10
  • 25