自动类型转换
介绍
-
当java程序在进行赋值或运算时,精度小的类型
自动转换
为精度大的数据类型 -
数据类型按精度(容量)大小排序为
char → int → long → float → double
byte → short → int → long → float → double
public class AutoConvert{
//自动转化
public static void main(String[]args){
int num = 'a'; // char → int
double d1 = 80; // int → double
System.out.println(num); //97
System.out.println(d1); //80.0
}
}
注
- 有多种类型的数据混合运算时,系统首先自动将所有数据
转换成
容量最大的数据类型,再计算。
public class AutoConvertDetail{
//自动类型转换细节
public static void main(String[]args){
int n1 = 10;
//float d1 = n1 + 1.1; 错误 n1 + 1.1 → 结果类型是 double
float d1 = n1 + 1.1; //正确 n1 + 1.1→ 结果类型啊 float
double d1 = n1 + 1.1F; //正确 n1 + 1.1 → 结果类型是 double
}
}
- 精度大的数据类型
赋值给
精度小的数据类型会报错
,反之进行自动转换。
int n2 = 1.1; //报错 double → int
- (byte ,short)和char之间不会相互自动转换。
//数值赋值 ,判断该数是否在byte范围内
byte b1 = 10; //正确 byte范围:-128 ~ 127
//变量赋值,判断类型
int n2 = 1;
byte b2 = n2; //错误 int占4个字节,byte占1个字节 无法赋值
char c1 = b1; //错误 byte不能自动转成char
- byte,short,char 三者可以计算,在计算时首先转换为int类型
short s2 = b2 + s1; //错误 b2 + s1 → int
int s2 = b2 + s1; //正确 b2 + s1 → int
- boolean不参与转换
boolean pass = true;
int num100 = pass; //报错
- 自动提升原则:表达式结果的类型自动提升为 操作数中最大类型
byte b4 = 1;
short s3 = 100;
int num200 = 1;
double num300 = 1.1;
double num500 = b4 + s3 + num200 + num300;//正确
强制类型转换
介绍
- 自动类型转换的逆过程,将容量大的数据类型
转换
为容量小的数据类型,使用时要加上强制转换符()
,但可能造成精度降低或溢出 。
int n1 = (int)1.9;
System.out.println("n1="+n1);
//精度损失
int n2 = 2000;
byte b1 = (byte)n2;
System.out.println("b1="+b1);
//数据溢出
}
}
注
- 当进行数据的从大到小转换,需要使用 强制转换
- 强制转换符号 只针对最近的操作数有效,往往会使用小括号提升优先级
int x = (int)10*3.5+6*1.5;
//只转换最近的10
int x = (int)(10*3.5+6*1.5);
//先计算括号里面得出44 再转换
- char类型可以保存int的常量值,不能保存int的变量值,需要强转
char c1 = 100; //正确
int m = 100; //正确
//char c2 = m;
//错误 int精度高与char无法自动转换
char c3 = (char)m; //正确 强制转换4
- byte , short ,char类型 进行运算时,做int类型处理
基本数据类型 转 字符串
介绍
- 基本类型 转 字符串
- 语法:
将基本类型的值
+“ ”
- 语法:
public static void main(String[]args)
int n1 = 100;
float f1 = 1.1F;
double d1 = 4.5;
boolean b1 = true;
String s1 = n1 + "";
String s1 = f1 + "";
String s1 = d1 + "";
String s1 = b1 + "";
System.out.println(s1 + " " + s2 + " " + s3 + " " + s4);
}
- 字符串 转 基本类型
- 语法: 通过基本类型的包装类调用parseXX方法
public static void main(String[]args){
String s5 = "123";
int num1 = Integer.parseInt(s5);
double num2 = Double.parseDouble(s5);
float num3 = Float.parseFloat(s5);
long num4 = Long.parseLong(s5);
byte num5 = Byte.parByte(s5);
boolean b = Boolean.parseBoolean("true");
short num6 = Short.parseShort(s5);
}
- string类型转 数据基本类型 , 要确保string类型能够转成有效数据
- 如果格式不正确,会抛出异常,程序终止