Java中主要有八种基本数据类型:
-
整型: byte、short、int、long
-
字符型:char
-
浮点型:float、double
-
布尔型:boolean
1.整数
- int为整数的默认类型
- long类型的值超出int的取值范围时必须在末尾添加L或者l(方便记忆,建议long类型所有值末尾直接添加L)
byte b=127;
short s=32767;
int i=1000000;
//在int的取值范围内
long l=1000;
//在int的取值范围外
long l2=10000000000L;
2字符型
- 单引号赋值:值内部只能有一个组成部分
char 变量名='值';
- 数值赋值:每个数字都有一个自己对应的字符,数字不能超出取值范围
A-Z:65-90
a-z: 97-122
char 变量名=数字;
- unicode编码赋值-了解
char 变量名='\u0041';//A
- char类型进行数学运算时会先统一换算为数值状态
char c1='a';
//char c2='ab';
char c2='6';
//char c3='65';
char c3=97;//a
char c4=6;
System.out.println(c1 == c3);//t
System.out.println(c2 == c4);//f
char c5='\u0041';
System.out.println(c5);//A
3.浮点型
- double为小数的默认类型
- float类型在赋值时末尾必须添加F或者f
4.布尔
- 无法进行数学运算
数据类型转换
类型从小至大:
byte–>short(char)–>int–>long–>float–>double
自动类型转换
- 发生在小类型给大类型赋值时(一定不存在风险)
大类型=小类型;
byte b=10;
//将byte类型的变量b的值赋值给short类型的s
short s=b;//short=byte
强制类型转换
- 发生在强制将大类型的值赋值给小类型时(存在风险)
小类型=(小类型)大类型;
- 大类型的值在小类型的取值范围内,不会出现数据异常
short s=10;
byte b=(byte)s;//10
- 大类型的值不在小类型的取值范围内,会出现数据异常
short s3=129;
byte b3 = (byte) s3;
System.out.println("b3: "+b3);//-127
- 小数转成整数时,会直接舍弃小数位,极有可能出现数据丢失
double d=5.9;
int n=(int) d;
System.out.println("n: "+n);//5
- 由于char类型没有负数取值,所有其他类型转为char时都需要进行类型强转
byte byte1=97;
char char1=(char) byte1;
-
boolean类型不参与数据类型转换
-
任意数据加上双引号或者拼接双引号都会变成String类型
String string1=byte1+"";
String string2=""+byte1;
String string3="100";
String string4= 5+6+"a" ;
System.out.println(string4);//11a
String string5= 5+"a"+6 ;
System.out.println(string5);//5a6
String string6= "a"+5+6 ;
System.out.println(string6);//a56
自动类型提升
发生在数学运算时,当有大类型参与时,会触发类型提升,最终结果将被提升为大类型
最多提升为double,最少提升为int
int num=10;
num=num+1;
//num=num+0.5;//int+double