java基本类型的转换原则

四个原则:
1、byte、char、short——>int ——>long——>float——>double,默认的自动转换方向。
2、byte、char、short类型不相互转化,而当他们参与运算时,都会转换成int类型再运算。
3、小数默认是double,整数默认是int。
4、都是final类型的byte、char、short类型在运算时,不会转换为int。

/**
 * 基本数据类型
 * @author jaybill
 * 四个原则:
 * 1、byte、char、short——>int ——>long——>float——>double,默认的自动转换方向。
 * 2、byte、char、short类型不相互转化,而当他们参与运算时,都会转换成int类型再运算。
 * 3、小数默认是double,整数默认是int。
 * 4、都是final类型的byte、char、short类型在运算时,不会转换为int。
 */
public class Test {
    public static void main(String [] args){
        byte b1 = 1;
        byte b2 = 2;        
        char c1 = '1';
        char c2 = '2';
        short s1 = 1;
        short s2 = 2;
        //以下五行说明,byte、short、char类型在运算的时候,会转换成int类型。当赋值时记得强制转换。
        byte b3 = (byte)(b1+b2);
        char c3 = (char)(c1+c2);
        short s3 = (short)(s1+s2);
        char c4 = (char)(b1+c1+s1);
        int tmp = c1+s1+b1;
        //以下说明,当byte、short、char类型声明为final的时候,进行运算不会转换成int,而能够根据左边的类型进行转换
        final byte b5 = 5;
        final char c5 ='5';
        final short s5 = 5;
        short s6 = b5+c5+s5;
    }
}

猜你喜欢

转载自blog.csdn.net/jaybill/article/details/69645088