参考JVM规范相关介绍,Java中各数据类型占用内存为:
byte:1字节
boolean:1字节(待定)
short:2字节
char:2字节
int:4字节
float:4字节
long:8字节
double:8字节
java.lang.Object:8字节
ref object:对象的引用4字节
return address:4字节
class A{
}
class B{
<span style="white-space:pre"> </span>int a;
<span style="white-space:pre"> </span>int b;
}
public class SizeOfTest {
<span style="white-space:pre"> </span>public static void main(String[] args) {
<span style="white-space:pre"> </span>//Java中所有类都是Object的子类,而java.lang.Object空壳对象本身占用8个字节
<span style="white-space:pre"> </span>System.out.println(SizeOf.sizeOf(new A()));//16=8+?
<span style="white-space:pre"> </span>System.out.println(SizeOf.sizeOf(new B()));//24=8+4*2+?
<span style="white-space:pre"> </span>}
}