Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatypes in Java and their representation

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?

like image 486
MacBeast Avatar asked Jul 03 '26 09:07

MacBeast


1 Answers

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
like image 111
Mick Mnemonic Avatar answered Jul 05 '26 22:07

Mick Mnemonic