public class Demo01Convert {
//自动类型转换练习一
public static void main(String[] args) {
int i = 1;
byte b = 2;
/*
报错:
i是int,b是byte,类型不一致,发生自动类型转换
byte + int --> int + int --> int
结果是占4个字节的int数据,不能直接赋值给左侧的占1个字节byte变量x
*/
//byte x = b + i;
/*
正确:
i是int,b是byte,类型不一致,发生自动类型转换
byte + int --> int + int --> int
结果是占4个字节的int数据,可以直接赋值给左侧的占4个字节int变量y
*/
int y = b + i;
System.out.println(y);//3
}
}
//自动类型转换练习二
public class Demo02Convert {
public static void main(String[] args){
int i = 1;
double d = 2.5;
/*
错误:
i是int类型,d是double类型,不一致,发生自动类型转换
double + int --> double + double --> double
结果是占8个字节的double数据,不可以直接赋值给占4个字节的int变量x
*/
//int x = d + i;
/*
正确:
i是int类型,d是double类型,不一致,发生自动类型转换
double + int --> double + double --> double
结果是占8个字节的double数据,可以直接赋值给占8个字节的double变量y
*/
double y = d + i;
System.out.println(y);//3.5
}
}
//强制类型转换练习一
public class Demo03Convert {
public static void main(String[] args){
long a = 888L;
/*
long类型的888:
00000000 00000000 00000000 00000000 00000000 00000000 00000011 01111000
强转成byte类型,砍掉左侧7个字节的内容:
01111000 ---> 十进制120
*/
byte b = (byte) a;
System.out.println(b);//120
long num = 6000000000L;
/*
long类型的6000000000L:
00000000 00000000 00000000 00000001 01100101 10100000 10111100 00000000
强转成int类型,砍掉左侧4个字节的内容: -2的32次方
01100101 10100000 10111100 00000000 ---> 十进制 1705032704
*/
int num2 = (int)num;
System.out.println(num2);
//short类型变量,内存中占2个字节
short s = 1;
/*
错误:
s是short类型,1是int类型,不一致,发生自动类型转换
short + int --> int + int --> int
结果是占4个字节的int数据,不能直接赋值给左侧的占2个字节的short变量s
解决方案:
把结果数据,强制类型转换
*/
//s = s + 1;
/*
正确:
s是short类型,1是int类型,不一致,发生自动类型转换
short + int --> int + int --> int
把占4个字节的int数据,强制转换成占2个字节的short数据,
就可以直接赋值给左侧的占2个字节的short变量s
解决方案:
把结果数据,强制类型转换
*/
s = (short) (s + 1);
System.out.println(s);//2
/*
+=,-=,*=等赋值运算符,如果结果类型和变量类型不一致,
内部会发生强制类型转换
*/
s += 1;//等价于: s = (short)(s+1)
System.out.println(s);//3
}
}
//强制类型转换练习二
public class Demo04Convert {
public static void main(String[] args){
//错误: 小数默认double占8个字节,不能直接赋值给占4个字节的int变量
//int j = 1.5;
//System.out.println(j);
/*
小数强转成整数: 直接砍掉小数部分,会损失精度
*/
int k = (int)1.5;
System.out.println(k);
/*
10默认是int类型,占4个字节
byte变量占1个字节
居然没有报错?
原因:
10是int类型的常量(不会变),没有超出byte的取值范围,
jvm内部帮助我们进行了强制类型转换
注意:
常量整数数字只要不超出赋值变量的范围,可以直接赋值
*/
byte a = 10;
System.out.println(a);
}
}
//char和int计算原理
public class Demo05Char {
public static void main(String[] args) {
char ch = 'a';
System.out.println(ch);//a
/*
byte/short/char 只要参加运算,至少要被转成int
char + int --> int + int --> int
问题:
如何把char,转换成int呢?
解决方案:
内部查看ASCII码表
'a' ----> 97
*/
System.out.println(ch + 1);//98
/*
byte/short/char 只要参加运算,至少要被转成int
char + int --> int + int --> int --> 把结果强转成char
问题:
如何把int,转换成char呢?
解决方案:
内部查看ASCII码表
98 ----> 'b'
*/
System.out.println((char)(ch + 1));//b
}
}
![](https://i-blog.csdnimg.cn/direct/cdd9112016af40f0b5a9d2cd6dda8f24.png)