how can i print out the type, size and range of a java data type ? esp those wtih modifiers?

谁说胖子不能爱 提交于 2019-12-13 11:19:24

问题


Currently i can print out the type size and range of a;; primitive java data types except bollean using the following method.

public class sizJ {

    public static void display(Class<?> type, int size, Number min, Number max) {
            System.out.printf("%-6s %-2s %-20s %s\n", type, size, min, max);
    }

    public static void main(String[] args) {
            System.out.printf("%s %-2s %-20s %s\n","type","size","min","max");
            display(Byte.TYPE, Byte.SIZE, Byte.MIN_VALUE, Byte.MAX_VALUE);
            display(Character.TYPE, Character.SIZE, (int) Character.MIN_VALUE, (int) Character.MAX_VALUE);
            display(Integer.TYPE, Integer.SIZE, Integer.MIN_VALUE, Integer.MAX_VALUE);
            display(Float.TYPE, Float.SIZE, Float.MIN_VALUE, Float.MAX_VALUE);
            display(Double.TYPE, Double.SIZE, Double.MIN_VALUE, Double.MAX_VALUE);
            display(Long.TYPE, Long.SIZE, Long.MIN_VALUE, Long.MAX_VALUE);
            display(Double.TYPE, Double.SIZE, Double.MIN_VALUE, Double.MAX_VALUE);

            display(SignedDouble.TYPE, Double.SIZE, Double.MIN_VALUE, Double.MAX_VALUE);
    }

}

Code copied from a forum.

The question is how can i print the same for, say signed long or signed char or unsigned int ?

Kindly help.


回答1:


Lots of things to clarify here...:

  1. Java does not have unsigned primitives like C - a significant issue, by the way, for those who need to do a lot of bit-twiddling, e.g. to implement a hash function. There is no unsigned keyword, no unsigned types and, of course, no corresposing type size.

  2. Java only has eight primitive types: boolean, byte, char, double, float, int, long, short

  3. Java also has eight corresponding classes, primarily used for autoboxing, but also to provide information on the primitive types, as seen in your sample code.

  4. Modifiers (e.g. public, final, static) only affect the visibility and access semantics of a primitive - not its basic properties, such as its size or range.

  5. The term "data type" also refers to object types. Java has no equivalent for the C sizeof operator, since you do not need it to allocate memory as in C. If you do need to know the memory footprint of an object have a look here.



来源:https://stackoverflow.com/questions/6614066/how-can-i-print-out-the-type-size-and-range-of-a-java-data-type-esp-those-wti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!