目录
一,数据类型的转换
1.基本数据类型之间的转换
2.字符串与其它数据类型的转换
3.其它实用数据类型转换
二,基本数据类型之间的转换

1.1,int转换为byte
public static void main(String[] args) {
int a = 20 ;
byte b= (byte) a;//大类型转换为小类型,需要强制转换
int c = b;//小类型转换为大类型,自动提升
}
需要注意
public static void main(String[] args) {
byte a = 127 ;
byte b= 130;//此处编译不通过是因为超过了byte取值范围
byte c = (byte) 130;//此处强制转换为byte类型
}
byte类型的取值范围-128到127
public static void main(String[] args) {
int a = 20;
byte b = a;//此处编译不通过是因为20虽然是取值范围内,
// 但是a为int类型,仍然需要强制转换
byte c = 10;
byte d = 15;
byte e = c + d;//此处编译不通过是因为计算机中数据的存取
// 是按4个字节进行的,c和d为int类型,需要强制转换
byte f = (byte)(c + d);//编译通过
}
不过上述情况使用final时,可以不用强制类型转换,因为final修饰的变量,数值和类型都不能改变,叫做最终变量,byte仍然为byte类型。
public static void main(String[] args) {
final byte c = 10;
final byte d = 15;
byte e = c + d;//编译通过
2.1,int转换为char类型
java对char类型的数据在底层是按int类型来处理的,由于java采用unicode编码,char 在java中占2个字节,用2个字节(16位)来表示一个字符。
public static void main(String[] args) {
char a ='g';
int b = a;//小类型转换为大类型,自动提升
int c = '龙';
char d = 69;
System.out.println(c);
System.out.println(d);
}

69被自动转换成unicode编码所对应的字符 ‘E’ ,字符 ‘龙’ 被自动转换成unicode码 40857
3.1,int和string类型的转换
1,使用字符串的拼接方法
public static void main(String[] args) {
int a = 20;
String str1 = "" + a;
System.out.println("str1:" + str1);
}
运行结果

2, 使用String类的静态方法 valueOf
public static void main(String[] args) {
int a = 20;
String str1 =String.valueOf(a);
System.out.println("str1:" + str1);
}
}
3,使用Integer类中的toString()方法,int转为Integer后再转为String
public static void main(String[] args) {
int num = 20;
Integer a =new Integer(num);
String str1 =a.toString();
System.out.println("str1:" + str1);
}
4,string转为int类型,使用Integer类中的parseInt()方法。
public static void main(String[] args) {
String str = "1000";
int a = Integer.parseInt(str);
System.out.println(a);
}
4.1,boolean数据类型
不能和其他数据类型进行转换,会出错
public static void main(String[] args) {
boolean a = true;
int b = (boolean) a;
}

5.1,int和double类型的转换
public static void main(String[] args) {
int a =20;
double b =(double) a;
System.out.println(b);
}










