Print Datatype to Console
October 10, 2022
Here's how to print the datatype of an object or a primitive value to the console:
- Object:
Object myobject = “new”; // note: String is an object
System.out.print(myobject.getClass().getName(); // java.lang.String
System.out.println(mystring.getClass().getSimpleName()); // String
- Primitive Value:
Values of primitive datatypes (byte, short, int, long, float, double, boolean, char) are no objects and have to be cast to an object first. Then you can use the .getClass() method on them, like so:
byte num = 1;
System.out.println(((Object)num).getClass().getName()); // java.lang.Byte
System.out.println(((Object)num).getClass().getSimpleName()); // Byte