数据类型
强类型语言
要求变量使用严格符合规定,所有变量必须定义后才能使用
弱类型语言
Java数据类型
基本类型
1、整型
byte 、short 、int 、long
2、浮点型
float 、 double
3、字符型
char
4、布尔型
boolean
名称 | 占用字节 | 默认值 | 封装器类 |
---|---|---|---|
byte(字节型) | 1 | 0 | Byte |
short(短整型) | 2 | 0 | Short |
int(整型) | 4 | 0 | Integer |
long(长整型) | 8 | 0.0l | Long |
float(浮点型) | 4 | 0.0f | Float |
double(双精度浮点型) | 8 | 0 | Double |
char(字符型) | 2 | \u0000(空格) | Character |
boolean(布尔型) | 1 | false | Boolean |
引用类型
- 类
- 接口
- 数组
例:
public static void main(String[] args) {
float a=0.1f;(结果为0.1)
float b=1.0/10;(结果为0.1)
System.out.println(a==b);
}
输出结果为flase
public static void main(String[] args) {
float a=4545456654f;
float b=a+1;
System.out.println(a==b);
}
输出结果为true
float 有限 离散 舍入误差 大约 接近不等于
float和double对数据判断不准确有误差,尽量不用浮点数去比较,需要用一个新的java数学类**BigDecimal **
字符
public static void main(String[] args) {
char c1='A';
char c2='中';
System.out.println(c1);
System.out.println((int)c1);//强转
System.out.println(c2);
System.out.println((int)c2);//强转
}
输出结果
所有字符的本质还是数字
编码Unicode表中:A=65,中=20013
转义字符
- \t 制表符
- \n 换行
-
-
-
-
-
- 等等
-
-
-
-
简单底层
String sa = new String("hello world");
String sb = new String("hello world");
System.out.println(sa==sb);
String sc = "hello world";
String sd = "hello world";
System.out.println(sc==sd);
布尔类型
boolean e=true;
if (e==true){}//if(e){}同样意思
类型转换
java是最强类型语言,所以运算时需要类型转换
低--------------------------------------------------------->高
byte,short,char–>int–>long–>float–>double
运算中不同数据类型的数据需要先转为同一类型后再进行运算
强制转换
int i=128;
byte b=(byte) i;//强转 内存溢出btye数据大小是从-128到127,内存溢出后循环从-128开始,
System.out.println(i);
System.out.println(b);
自动转换(低转到高不需要强转)
int o=128;
double p= i;//自动转换
System.out.println(o);
System.out.println(p);
注意点
-
不能对布尔类型进行转换true和flase
-
不能把对象类型转换为不相干的类型
-
转换的时候可能存在内存溢出
-
转换的时候还可能出现精度问题。例:如果将double类型的22.2转换为int类型最后输出的值为22