Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master'
Browse files Browse the repository at this point in the history
  • Loading branch information
MidnightDancing committed Jun 10, 2019
2 parents c4f77f8 + 1734873 commit de89c80
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 5 deletions.
46 changes: 41 additions & 5 deletions doc/basetype.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,58 @@ java支持的数据类型分为两类:基本数据类型 和 引用类型。

> char代表字符型,实际上字符型也是一种整数类型,相当于无符号整数类型。
![](../images/basetype1.jpg)
![](../images/doc/basetype1.jpg)

**基本数据类型和引用类型的区别**

![](../images/basetype2.jpg)
![](../images/doc/basetype2.jpg)

## 基本类型的类型转换

java语言的7种数值类型之间可以进行类型转换,分为两种:自动类型转换 和 强制类型转换

#### 自动类型转换

发生条件:当该数据类型的数值表示范围小于另一种数据类型的数值表示范围时,进行自动类型转换
发生条件:
- 1.赋值运算:当该数据类型的数值表示范围小于另一种数据类型的数值表示范围时,赋值运算会进行自动类型转换。
- 2.表达式自动提升:当一个算术表达式中包含多个基本类型的值时,整个算术表达式的数据类型发生自动提升。整个算术表达式的数据类型自动提升到与表达式中最高等级操作数同样的类型。

![](../images/basetype3.jpg)

![](../images/doc/basetype3.jpg)

> 这里我们所说的“大”与“小”,并不是指占用字节的多少,而是指表示值的范围的大小。
举例说明:java的浮点数采用二进制数据的科学计数法来表示,比如:对于float类型,第1位是符号位,接下来8位表示指数,再接下来的23位表示尾数
举例说明:

```
long x = 30;
float y = 14.3f;
System.out.println("x/y = " + x/y);
```
输出:
```
x/y = 1.9607843
```

long类型的长度为8个字节,占64位,表示范围为 -2^63 - (2^63 - 1)

float类型的长度为4个字节,占32位,表示范围为超过 -2^128 - 2^128

java的浮点数采用二进制数据的科学计数法来表示,对于float类型,第1位是符号位,接下来8位表示指数,再接下来的23位表示尾数.
由于float的指数部分对应的指数范围为-128~128,所以取值范围为:-2^128到2^128;精度(有效数字)看尾数位:
float的尾数位是23位,对应7~8位十进制数,所以有效数字有的编译器是7位,也有的是8位。

#### 强制类型转换

发生条件:

- 当试图强制把表数范围大的类型转换为表数范围小的类型时

示例:
```
float f = 25.5f;
int x = (int)f;
System.out.println("x = " + x);
```

## 保持数据精度
Binary file removed images/basetype2.jpg
Binary file not shown.
File renamed without changes
Binary file added images/doc/basetype2.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes

0 comments on commit de89c80

Please sign in to comment.