您的位置:首页 > 博客中心 > 编程语言 >

Java中的变量类型转换

时间:2022-03-29 01:41

自动类型转换

byte b=3;
int x=b;//将byte类型的变量b转换为int类型无需特殊声明

强制类型转换

两种类型不兼容,或者目标类型取值范围小于源类型时,自动类型转换无法进行,这时需要强制类型转换。
如:

public class test {
	public static void main(String[] args) {
	int num=298;
	byte b=num;
	System.out.println(b);
}
}

会报错,提示我们将num强制转换为byte类型:

public class test {
	public static void main(String[] args) {
	int num=298;
	byte b=(byte)num;
	System.out.println(b);
}
}

输出42
这是由于byte是1字节,只有八位,int是4字节有32位,前面三个字节的数据就会丢失
也就是00000000 00000000 00000001 00101010变成了00101010

本类排行

今日推荐

热门手游