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.T开发者_高级运维YPE, 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.
Lots of things to clarify here...:
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.Java only has eight primitive types:
boolean
,byte
,char
,double
,float
,int
,long
,short
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.
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.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.
Java has no sizeof operator to find the size of primitive data types but all Java primitive wrappers except Boolean provide an SIZE constant in bits that could be divided by eight to get the size of a data type in bytes.
class SizePrimitiveTypes
{
public static void main (String[] args)
{
System.out.println("Size of byte: " + (Byte.SIZE/8) + " bytes.");
System.out.println("Size of short: " + (Short.SIZE/8) + " bytes.");
System.out.println("Size of int: " + (Integer.SIZE/8) + " bytes.");
System.out.println("Size of long: " + (Long.SIZE/8) + " bytes.");
System.out.println("Size of char: " + (Character.SIZE/8) + " bytes.");
System.out.println("Size of float: " + (Float.SIZE/8) + " bytes.");
System.out.println("Size of double: " + (Double.SIZE/8) + " bytes.");
}
}
精彩评论