I have question about primitive types in Java (int, double, long, etc).
Question one:
Is there a way in Java to have a datatype, lets say XType (Lossless type) that can hold any of the primitive types?
Example of hypothetical usage:
int x = 10;
double y = 9.5;
XType newTypeX = x;
XType newTypeY = y;
int m = newTypeX;
Question two:
Is there away to tell from the bits if this number (primitive type) is an integer, or a double, or a float, etc?
You can use the Number class, which is the super class for all numeric primitive wrapper classes, in your first snippet:
int x = 10;
double y = 9.5;
Number newTypeX = x;
Number newTypeY = y;
The conversion between the primitive types (int, double) and the object type (Number) is possible through a feature called autoboxing. However, this line won't compile:
int m = newTypeX;
because you cannot assign the super type variable into an int. The compiler doesn't know the exact type of newTypeX here (even if it was assigned with an int value earlier); for all it cares, the variable could as well be a double.
For getting the runtime type of the Number variable, you can e.g. use the getClass method:
System.out.println(newTypeX.getClass());
System.out.println(newTypeY.getClass());
When used with the example snippet, this will print out
class java.lang.Integer class java.lang.Double
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With