一、自动转换
基本数据类型在计算的时候都会向数值范围大的方向转换。
byte -> short -> int -> lon -> float -> double
1、数据类型转换规则:
①所有的byte类型和short类型和char值运算的时候都会提供成int类型,int最大值2147483647.
public class helloWorld{
public static void main(String[] args)
{
//定义一个字节类型
byte b = 1;
int b1 = b+1;
short b2 = 12;
//byte、short、int、char,四中类型在发生计算都会自动把结果提升为int类型
int = b+b2;
//定义一个char类型,字符和整数类型可以自定转换
char c = 'a';
int ie = c+1;
}
}
2、如果计算中一个操作数据是long,另一个数的空间小于等于long,那么结果就是long。
3、如果计算中一个操作数据是float,另一个数的空间小于等于float, 那么结果就是float。
4、如果计算中一个操作数据是duoble,另一个数的空间小于等于double ,那么结果就是double。
public class helloWorld{
public static void main(String[] args)
{
//如果两个int类型计算会不会自动提升类型呢?
int x = 2147483647;
int y = 22;
//int、long、float、double,自身计算时不会提升类型,如果超出了范围就会出现精度的损失
int z = x + y;
System.out.println(z);
float f = 1.3f;
//int类型和float类型转换成float
float f1 = f + y;
//小数的常量默认值是double
double d = f + 1.3;
//12.5是表示float类型的常量,小的表数范围的常量或者变量可以自动的向大的表数类型转换
double d1 = 12.5F;
}
}
二、强制转换
当大容量类型的变量向小容量类型的变量去转换需要强制转换。
public class helloWorld{
public static void main(String[] args)
{
int i = 999;
//数值类型转换的前提是精度不会损失,i的值是999,转换成byte类型,byte的数值最大范围是127,所以强制转换会损失精度
byte b = (byte)i;
System.out.println(b);
//定义long类型
long j = 10000;
int y = (int)j;
System.out.println(y);
//小数类型的强转
float f = 199.5f;
//转换成int,小数转换成整数就是把小数点后面去掉
int f1 = (int)f;
System.out.println(f1);
//double向float转换
double d = 10.4;
float f2 = (float)d;
System.out.println(f2);
//字符的转换,char属于自动转
char c = 'a';
int x = c;
System.out.println(x);
//int转换为字符类型
int g = 98;
char g1 = (char)g;
//输出对应的字符b;
System.out.println(g1);
}
}