Java的八种基本数据类型及其大小:

 

Java的八种基本数据类型:

数据类型名称大小(B) 注:1B = 8b包装器
byte字节型1Byte
short字符型2Short
int短整型4Integer
long整形8Long
float单精度浮点型4Float
double双精度浮点型8Double
char字符型2Character
boolean布尔不同情况下不同Boolean

  注:布尔类型不同情况下使用的空间不一致,大致有如下几种情况:

 1.单个的boolean 类型变量在编译的时候是使用的int 类型

boolean a=true;//这个a在JVM中占4个字节即:32位。

 2.boolean 类型的数组时,在编译的时候是作为byte array来编译的所以boolean 数组里面的每一个元件占一个字节

boolean[] b = new boolean[10];//数组时,每一个boolean在JVM中占一个字节。

理由:

1)JAVA规范中没有定义boolean类型的大小。

2)但是:在JVM规范第2版中讲得十分清楚。我上边的结论就是从它当中取出来的。

根据:(JVM规范第2版 3.3.4节)

Instead, expressions in the Java programming language that operate on boolean values are compiled to use values of the Java virtual machine int data type.  

Where Java programming language boolean values are mapped by compilers to values of Java virtual machine type int, the compilers must use the same encoding. 而:Java virtual machine type int, whose values are 32-bit signed two's-complement integers。

Arrays of type boolean are accessed and modified using the byte array instructions  

In Sun's JDK releases 1.0 and 1.1, and the Java 2 SDK, Standard Edition, v1.2, boolean arrays in the Java programming language are encoded as Java virtual machine byte arrays, using 8 bits per boolean element.

3. 也有说都是1bit的,仁者见仁智者见智,具体还是要看JVM是不是按照他的说明来做的。

 

基本数据类型的运算和转换:

基本数据类型进行运算时分为自动转换和强制转换:

1.自动转换 (小 -> 大)

当范围‘小’的数据和字节‘大’的数据运算时,系统自动将小数据转换成大数据进行运算。这些类型由"小"到"大"分别为 (byte,short,char)--int--long--float—double;

byte b;int i=b; long l=b; float f=b; double d=b;//此语句可以在Java中直接通过:

注意char -> int 时,int 将会保存其ASCII码。

2.强制转换 (大 -> 小)

short i=99 ;
char c=(char)i;
System.out.println("output:"+c);
//对于byte,short,char三种类型而言,他们是平级的

注意:

①所有的byte,short,char型的值将被提升为int型;

②如果有一个操作数是long型,计算结果是long型;

③如果有一个操作数是float型,计算结果是float型;

④如果有一个操作数是double型,计算结果是double型;

例, byte b; b=3; b=(byte)(b*3);//必须声明byte。

 

学完了,给大家补全个细节性问题:

提问:short b = 3; 操作1: b = b + 1; 操作2:b += 1;这两种操作方式都正确?

解答:操作1不正确,因为b时short,b + 1的1是int, 赋值给b的时候会出现类型问题(int ->long).所以要对运算后值进行类型强转;

short b = 2;
b = (short)(b + 1);

操作2正确:

后面一句没有错是因为Java语言规范中讲到,复合赋值(E1 op=E2)等价于简单赋值(E1=(T)((E1) op (E2))),而(s1 += 1)表达式使用的是复合赋值操作符,复合赋值表达式自动地将所执行计算的结果转型为其左侧变量的类型。如果结果的类型与该变量的类型相同,那么这个转型不会造成任何影响。

 

 

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值