Java基本数据类型的装换

Java基本数据类型的装换顺序以下所示:
低 ------------------------------------> 高code

byte,short,char—> int —> long—> float —> double 
由低到高装换:Java基本数据类型由低到高的装换是自动的.而且能够混合运算,必须知足转换前的数据类型的位数要低于转换后的数据类型,例如: short数据类型的位数为16位,就能够自动转换位数为32的int类型,一样float数据类型的位数为32,能够自动转换为64位的double类型 好比:对象

/**
 * 基本数据类型的转换
 *
 */
public class Convert {
    public static void main(String[] args) {
        upConvert();
        System.out.println("=====================我是分割线========================");
        downConcert();
    }

    /**
     * 向上转换
     */
    public static void upConvert(){
        char c = 'a';
        byte b = (byte) c;
        short s = b;
        int i = s;
        long l = i;
        float f = l;
        double d = f;
        System.out.println(c);
        System.out.println(b);
        System.out.println(s);
        System.out.println(i);
        System.out.println(l);
        System.out.println(f);
        System.out.println(d);
    }

    /**
     * 向下转换
     */
    public static  void  downConcert(){
        double d = 97.0;
        float f = (float) d;
        long l = (long) f;
        int i = (int) l;
        short s = (short) i;
        byte b = (byte) s;
        char c = (char) b;
        System.out.println(c);
        System.out.println(b);
        System.out.println(s);
        System.out.println(i);
        System.out.println(l);
        System.out.println(f);
        System.out.println(d);

    }
}

运行结果为:
a
97
97
97
97
97.0
97.0
=====================我是分割线========================
a
97
97
97
97
97.0
97.0
注意:
数据类型转换必须知足以下规则:
1. 不能对boolean类型进行类型转换。
2. 不能把对象类型转换成不相关类的对象。
3. 在把容量大的类型转换为容量小的类型时必须使用强制类型转换。get

阅读全文请点击class

相关文章
相关标签/搜索