【基础语法】short、int、long转为byte

以下为错误代码

public class firstClass {
    public static void main(String[] args) {
        byte num1 = 1;
        short num2 = 2;
        int num3 = 3;
        long num4 = 4L;
        
        //转换byte
        short n2 = (byte)(num2);
        int n3 = (byte)(num3);
        long n4 = (byte)(num4);
        
        //转换long
        long s1 = num1;
        long s2 = num2;
        long s3 = num4;
        
    }
}

以下为正确代码

public class firstClass {
    public static void main(String[] args) {
        byte num1 = 1;
        short num2 = 2;
        int num3 = 3;
        long num4 = 4L;
        
        //转换byte,显式转换
        byte n2 = (byte)num2;
        byte n3 = (byte)num3;
        byte n4 = (byte)num4;
        
        //转换long,隐式转换
        long s1 = num1;
        long s2 = num2;
        long s3 = num4;
        
    }
}
posted @ 2024-04-04 00:06  H_one  阅读(7)  评论(0编辑  收藏  举报