JAVA中的隐式转换

本文详细解析了Java中的数据类型隐式转换规则,包括byte、short、char类型的自动提升为int,以及不同类型间计算时的转换机制。同时,通过实例展示了强制类型转换可能导致的错误,强调了在进行类型转换时需注意的细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package HelloWorld1;

public class YinShiZhuanHuan {
	public static void main(String[] args) {
		byte a=100; // byte类型的范围是-128~127
		short b=30000;// short 范围是-32768~32767
		char s=10000;// char 表示一个字符如“a","A","0","你”
		boolean x=true;// java里面的true所有字符小写,python里面首字母要大写
		//byte,short,char,默认转换成int(-2147483648~2147483648)<long<float<double
		boolean y=false;// 
		System.out.println(a+b+s);//java 中字符串也可以和数字直接相加,而python中是不可以的
		System.out.println(x);
		System.out.println(y);
	}
}

运行结果:

40100
true
false

package HelloWorld1;

public class YinShiZhuanHuan {
	public static void main(String[] args) {
		byte a=100; // byte类型的范围是-128~127
		short b=30000;// short 范围是-32768~32767
		char s=10000;// char 表示一个字符如“a","A","0","你”
		boolean x=true;// java里面的true所有字符小写,python里面首字母要大写
		boolean y=false;// 
		byte a1=25;
		short a2=10000;
		short a3=a1+a2;
		System.out.println(a+b+s);//java 中字符串也可以和数字直接相加,而python中是不可以的
		System.out.println(x);
		System.out.println(y);
		//System.out.println(a1+a2);
		System.out.println(a3);
	}
}

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Type mismatch: cannot convert from int to short

	at HelloWorld1.YinShiZhuanHuan.main(YinShiZhuanHuan.java:12)

byte,short,char之间计算的时候如果print(a+b)
java会根据计算数值的大小自行转换成int,long,float,double
如果强制定义short c=a+b print© 那么就会报错,因为int,long,float,double 不可以转换成byte,short,char

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值