021- Java语言基础-基本数据类型的一些问题和总结

我们输入以下代码:

public class DataType07
{
    public static void main(String[]args){
    
    byte b1 = 4;
    byte b2 = 5;
    byte b3 = b2 + b1;
    System.out.println(b3);   
    }
}

在命令行编译如下:

021- Java语言基础-基本数据类型的一些问题和总结

我们发现报错了,不兼容的类型,程序运行的时候,会将b1和b2转换成iint类型,然后再做加法运算。

所以我们应该这样做,输入以下代码:

public class DataType07
{
    public static void main(String[]args){
    
    byte b1 = 4;
    byte b2 = 5;
    //byte b3 = b2 + b1;   error 不兼容的类型,程序运行的时候,会将b1和b2转换成iint类型,然后再做加法运算。
    //System.out.println(b3);  

    byte b3 = (byte)(b1+b2);
    System.out.println(b3);
    
    }
}

命令行解释如下:

021- Java语言基础-基本数据类型的一些问题和总结

我们是把b1+b2强制转换成了byte类型。

在输入以下这段代码:

public class DataType07
{
    public static void main(String[]args){
    
    byte b1 = 4;
    byte b2 = 5;
    //byte b3 = b2 + b1;   error 不兼容的类型,程序运行的时候,会将b1和b2转换成iint类型,然后再做加法运算。
    //System.out.println(b3);  

    byte b3 = (byte)(b1+b2);
    System.out.println(b3);


    byte b4 = 10;
    short s1 = 5;
    int i1 = b4 + s1 ;
    System.out.println(i1);

    
    }
}

 命令行结果为:

021- Java语言基础-基本数据类型的一些问题和总结

我们可以看到是没有报错的,因为程序会默认把byte类型的数字与short类型的数字自动转换成int类型。

然后看一下代码:

public class DataType07
{
    public static void main(String[]args){
    
    byte b1 = 4;
    byte b2 = 5;
    //byte b3 = b2 + b1;   error 不兼容的类型,程序运行的时候,会将b1和b2转换成iint类型,然后再做加法运算。
    //System.out.println(b3);  

    byte b3 = (byte)(b1+b2);
    System.out.println(b3);


    byte b4 = 10;
    byte s1 = 5;
    int i1 = b4 + s1 ;
    System.out.println(i1);
    
    char c1 = 'a';//97
    int i2 = c1+100;
    System.out.println(i2) //197
    System.out.println((byte)c1);

    }
}

总结:

关于基本数据类型转换规则:

1.8种基本数据类型除boolean类型之外都可以相互转换.

2.小容量向大容量转换叫做自动类型转换:byte<short(char)<int<long<float<double

3.byte,short,char做混合运算的时候,各自都先转换成int在做运算

4.大容量向小容量转换是强制类型转换,需要加强制转换符,编译虽然通过,运行期可能损失精度。谨慎使用。

5.如果整数没有超出byte,short,char的取值范围,可以直接将这个整数赋值给byte,short,char

6.多种数据类型做混合运算,先转换成容量最大的那种再做运算。