用代码来测试JAVA中数据类型的存储大小

感谢优快云 jack_chen


import java.io.*;

public class abc {

public static void main(String[] args) {

char cr = 1;
byte be = 1;
short st = 1;
int it = -1;
long lg = 1;
float ft = 1;
double de = 1;

int cnt;
byte x;
int cot = 0;
int byteSize = 0;

// System.out.println("Float.size: "+Float.SIZE);
// System.out.println("Double.size: "+Double.SIZE);

for (cnt = 1; (cr <<= 1) != 0; cnt++)
;
System.out.println("char'sBits:" + cnt);

for (cnt = 1; (be <<= 1) != 0; cnt++)
;
System.out.println("byte'sBits:" + cnt);
byteSize = cnt;

for (cnt = 1; (st <<= 1) != 0; cnt++)
;
System.out.println("short'sBits:" + cnt);

for (cnt = 1; (it <<= 1) != 0; cnt++)
;
System.out.println("int'sBits:" + cnt);

for (cnt = 1; (lg <<= 1) != 0; cnt++)
;
System.out.println("long'sBits:" + cnt);

// 用字节流处理double
try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
out.writeDouble(de);
out.close();
DataInputStream in = new DataInputStream(new ByteArrayInputStream(
buf.toByteArray()));

while ((x = (byte) in.readByte()) != -1) {

// System.out.println("byte["+cot+"]:"+x);
cot++;
}
in.close();

} catch (IOException e) {
System.out.println("EOF!!!");
}
System.out.println("The Double's bit size is :" + cot * byteSize);

// 用字节流处理float
try {
cot = 0;
ByteArrayOutputStream buf = new ByteArrayOutputStream();
DataOutputStream out = new DataOutputStream(buf);
out.writeFloat(ft);
out.close();
DataInputStream in = new DataInputStream(new ByteArrayInputStream(
buf.toByteArray()));

while ((x = (byte) in.readByte()) != -1) {

// System.out.println("byte["+cot+"]:"+x);
cot++;
}
in.close();

} catch (IOException e) {
System.out.println("EOF!!!");
}
System.out.println("The Float's bit size is :" + cot * byteSize);

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值