Java中存在多个基本数据类型,如:int、float、double、short等。在实际应用中,我们有可能需要获取这些类型的字节数,获取数据类型的字节数可以通过直接写的方式,因为java中基本数据类型的长度是固定的。这里介绍另一种方式。
我们可以使用基本类型的封装类型的SIZE常量,该常量用来以二进制补码形式表示基本数据类型值的比特位数。
package com.bug315;
public class IntTest {
public static void main(String[] args) {
int intSize = Integer.SIZE;
System.out.println(" int size: " + (intSize/8) + "Byte" );
int shortSize = Short.SIZE;
System.out.println(" short size: " + (shortSize/8) + "Byte" );
int longSize = Long.SIZE;
System.out.println(" long size: " + (longSize/8) + "Byte" );
int byteSize = Byte.SIZE;
System.out.println(" byte size: " + (byteSize/8) + "Byte" );
int floatSize = Float.SIZE;
System.out.println(" float size: " + (floatSize/8) + "Byte" );
int doubleSize = Double.SIZE;
System.out.println(" double size: " + (doubleSize/8) + "Byte" );
}
}
输出结果:
int size: 4Byte
short size: 2Byte
long size: 8Byte
byte size: 1Byte
float size: 4Byte
double size: 8Byte