1. 基本数据类型
数据类型 | 二进制位数 | 对应的包装类 | 默认值 |
---|---|---|---|
byte | 8 | java.lang.Byte | 0 |
short | 16 | java.lang.Short | 0 |
int | 32 | java.lang.Integer | 0 |
long | 64 | java.lang.Long | 0L |
float | 32 | java.lang.Float | 0.0f |
double | 64 | java.lang.Double | 0.0d |
char | 16 | java.lang.Character | ‘u.000’ |
boolean | false |
注意:float类型和double类型可以用科学计数法表示
public static void main(String[] args) {
float a1=0.005f;
float a2=5E-3f;
double b1=0.003d;
double b2=3e-3d;
System.out.println("a1=:"+a1);
System.out.println("a2=:"+a2);
System.out.println("b1=:"+b1);
System.out.println("b2=:"+b2);
}
// a1=:0.005
// a2=:0.005
// b1=:0.003
// b2=:0.003
2. 基本数据类型转换
-
自动类型转换:基本类型不同的两个变量运算时,范围小的变量会自动转换成另一个变量相同的数据类型运算。具体如下:
- char(字符型)以及byte,short,int,long类型(整型)互相运算时,小范围转换成大范围类型
public static void main(String[] args) { byte sum1; byte a = 5; int b = 6; sum=a+b; System.out.println(sum); //错误:(17, 14) java: 不兼容的类型: 从int转换到byte可能会有损失 }
- 比int小的整型(byte,short)以及字符型(char)互相运算时,默认统一转换成int类型进行运算
- 整型和float,double(浮点型)运算时,整型会转换成浮点型
public static void main(String[] args) { long a=55L; float b= 3f; float sum = a + b; System.out.println(sum);//58.0 }
- float和double之间进行运算时,float会自动转换为double类型。
-
强制类型转换:把范围大的类型强制转换成取值范围小的类型.可能会发生精度损失,如下所示
public static void main(String[] args) { int a = (int) 5.1; int b = (int)5.2f; byte c = (byte)130; System.out.println(a);//5 System.out.println(b);//5 System.out.println(c);//-126 }
3.包装类
因为基本类型没有方法和属性,为了便于数据表的操作,每个基本类型对应一个包装类,使得基本数据类型对象化。
- 两个基本概念:
- 装箱:基本数据类型转换成包装类
- 拆箱:包装类转换成基本类型
- 自动拆装箱、手动拆装箱
public static void main(String[] args) { Integer a=2; //自动装箱 int b=a; //自动拆箱 Integer c = new Integer(2); //手动装箱 int d = a.intValue(); //手动拆箱 }
- 包装类中的常用方法(以Integer为例)
static Integer parseInt(String s)
:返回字符串表示的对应类型的包装类。