数据类型自动转换
精度小的类型自动转换为精度大的类型
以下是转换顺序:
char->int->long->float->double
byte->short->int->long->float->double
public class bdtc{
public static void main(String[] args){
//q从字符类型char转换成int类型
int a='q';
//100从整数类型int转换成double类型
double b=100;
//int类型转换成float类型
int c=10;
float d=c+1.1F;
//int类型转换成double类型
double e=c+1.1;
//float f=c+1.1;数据丢失
System.out.println(a);
System.out.println(b);
System.out.println(d);
System.out.println(e);
}
}
byte\short与char不可相互转换
布尔类型boolean不参与转换
多种数据混合运算时会先转换成精度大的运算后转换成精度小的
数据类型强制转换
将精度大的数据类型强制转换为精度小的类型
public class ct{
public static void main(String[] args){
int a=(int)1.1;
byte b=(byte)a;
System.out.println("a:"+a);
System.out.println("b:"+b);
}
}
String类型转换
基本数据类型->String类型
格式:
String a= int b+” ”;
String类型->基本数据类型
格式:
Integer.parseInt(“123”);
Double.parseDouble(“123.1”);
Float.parseFloat(“123.12”);
Short.parseShort(“123”);
Long.parseLong(“123”);
Boolean.parseIBoolean(“true”);
Byte.parseByte(“13”);
public class stc{
public static void main(String[] args){
//基本数据类型->String类型
int a=11;
char b='a';
float c=2.2F;
double d=3.1;
boolean e=true;
String f1=a+" ";
String f2=b+" ";
String f3=c+" ";
String f4=d+" ";
String f5=e+" ";
//String类型->基本数据类型
String g="12";
int h1=Integer.parseInt(g);
double h2=Double.parseDouble(g);
float h3=Float.parseFloat(g);
short h4=Short.parseShort(g);
long h5=Long.parseLong(g);
boolean h6=Boolean.parseBoolean("true");
byte h7=Byte.parseByte(g);
System.out.println("基本数据类型->String类型\nf1="+f1+"\nf2="+f2+"\nf3="+f3+"\nf4="+f4+"\nf5="+f5);
System.out.println("\nString类型->基本数据类型\nh1="+h1+"\nh2="+h2+"\nh3="+h3+"\nh4="+h4+"\nh5="+h5+"\nh6="+h6+"\nh7="+h7);
}
}
转换例题
1.int->byte强制转化
2.混合运算(char\int\float)->double自动转换
public class samp1{
public static void main(String[] args){
byte a=9;
char b='a';
int c=1;
float d=13.1F;
System.out.println("byte a="+(byte)(a+11));
System.out.println("double e="+(b+c+d));
}
}