### 1.基本类型(primitive type)
一位(bit)就是一个2进制数,0/1
1字节=8bit
一个16进制数可由4个二进制位表示
2个16进制数占一个字节
数值类型
- 整数类型
1.byte,1个字节,-128~127
2.short,2个字节,-32768~32767
3.int,4个字节,-2147483648~2147483647
4.long,8个字节,-9223372036854775808~9223372036854775807 - 浮点类型
1.float,4个字节
2.double,8个字节 - 字符类型(char):2个字节
boolean:
占32位=4个字节
2.引用类型(reference type)
- 类
- 接口
- 数组
3.整数拓展
//整数拓展
int a0 = 20; // 十进制
int a1 = 020; // 八进制0
int a2 = 0x20; // 十六进制0x
4.浮点数拓展
尽量避免使用浮点数比较大小
可以使用java.math.BigDecimal类进行大数的比较大小
float f = 0.1f;
double d = 1.0/10;
System.out.println(f);
System.out.println(d);
System.out.println(f==d);
System.out.println("-----------------------------------------");
float a1 = 22222233333f;
float a2 = a1+1;
System.out.println(a1);
System.out.println(a2);
System.out.println(a1 == a2);
运行结果:
0.1
0.1
false
-----------------------------------------
2.22222336E10
2.22222336E10
true
原理:float表示的浮点数是有限的,但很多浮点数是无限的,在没法精确表示一个浮点数的时候,底层就会利用‘舍入误差’,用一个接近但不等于的数表示
浮点数在计算机中的表示,float(32位)
0/1(符号位) 0 0 0 0 0 0 0 0 (8位阶位,0-255) 0 0 0 0 ...0 0 0 0(23位数值位)62534
m
表示范围:2^(m-127)*62534
浮点数精度:距离0越近,精度越高,距离0越远,精度越低,浮点数的阶数位越大,数值位相同增量的情况下数值增量越大,精度下降
二进制表示double和float都是不准确的,因为二进制数不能表示所有的数,例如0.1
5.字符拓展
所有的字符本质还是数字,Unicode编码,每个字符都对应一个数值
可以使用(int)+字符变量强转查看
char a='a';
char z='我';
System.out.println(a);
System.out.println((int)a);
System.out.println(z);
System.out.println((int)z);
结果显示:
a
97
我
25105
还可以直接使用Unicode码定义字符串:
char c='\u0063';//字符c
6.String对象
String s1=new String("helloworld");
String s2=new String("helloworld");
System.out.println(s1==s2);//false
String a1="helloworld";
String a2="helloworld";
System.out.println(a1==a2);//true
7.类型转换
byte,short,char->int->long->float->double
//占用内存:低---------------------------------->高
运算时,不同类型先转换为同一类型,再进行运算
低到高是自动类型转换
高到低是强制类型转换,强制类型转换要考虑内存溢出的问题,还有精度问题(浮点数到整数)
例如:
int a=128;
byte b=(byte)a;
System.out.println(a);//结果是128
System.out.println(b);//结果是-128
大数操作注意:
int a=10_0000_0000;//方便观察的写法
int b=20;
int total=a*b;//-1474836480,结果太大,内存溢出
long total1=a*(long)b;//正确写法