【基礎語法】short、int、long轉為byte

H_one發表於2024-04-04

以下為錯誤程式碼

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;
        
    }
}