Java(四)Java数据类型
Java是强类型语言,严格区分大小写,而且,必须要先定义,再使用。
Java数据类型分为基本类型和引用类型。
基本类型
八大基本类型:
- byte
- short
- int
- long
- float
- double
- char
- boolean
public class DataType {
public static void main(String[] args){
int num1 = 1000; // 4字节
byte num2 = 13; // 1字节
short num3 = 123; // 2字节
long num4 = 123L; //8字节,long类型的数据后面要加上一个L,最好写大写L,避免和数字1弄混
float num5 = 20.1f; //float类型的数据后面要加上一个f
double num6 = 3.12459343;
char num7 = '3';
String num8 = "test"; //String不是基本数据类型,是类
boolean flag = true; // 是、否
System.out.println(num1);
System.out.println(num2);
}
}
引用类型
非基本类型的都是引用类型,比如String,或者自己定义的类
类型转换
- 低容量转高容量,自动类型转换;
int num211 = 32767+1;
System.out.println(num211); // 输出32768
- 高容量转低容量,需要强制转换,可能会丢失精度
int num1 = 2147483647;
short num111 = (short)num1; // 输出-1,损失精度
整型转换的小例子
short a = 0x7fff;
short b = (short)(a+1); //这个时候精度已经丢失了
int c = b;
System.out.println(c); //-32768
int d = a +1; // 这个就不会溢出
System.out.println(d); //32768
int e = 0x7fffffff;
int f = e+1; //溢出
long g= f;
System.out.println(g); //-2147483648
int h = 0x7fffffff;
long i = h+1; //还是会溢出,计算过程中使用的是eax寄存器,只有32位
System.out.println(i);
注意点
- 要避免溢出,就需要先转换类型,再做计算
int j = 0x7fffffff;
long k = (long)j+1;
System.out.println(k); //2147483648
int num1= 1_0000_0000; //太长的数字,中间可以用下划线连接
long num2 = (long)num1 * 10000;
System.out.println(num2);
- float类型的长度是有限的的,高精度的数据尽量不要用float存储
//float类型的数据以f结尾
float a = 0.1f;
double b = 1/10;
System.out.println(a==b); //结果是false
float c = 12121212121121212f;
float d = c+1;
System.out.println(c==d); //结果是true,float长度有限,精度丢失