阅读491 返回首页    go 阿里云 go 技术社区[云栖]


Java基本数据类型的装换

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

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. 在把容量大的类型转换为容量小的类型时必须使用强制类型转换。
4. 转换过程中可能导致溢出或损失精度 比如:

/**
 * byte类型的最大值我127
 * 当int的值为128是就会溢出
 */
public class Test {
    public static void main(String[] args) {
        int i = 128;
        byte b = (byte) i;
        System.out.println(i);
        System.out.println(b);
    }
}

  1. 浮点数到整数的转换是通过舍弃小数得到,而不是四舍五入
class Test2{
    public static void main(String[] args) {
        int i = (int) 23.7;
        System.out.println(i);
    }
}

明天开始接接触Java变量的申明及使用.

最后更新:2017-05-22 20:31:18

  上一篇:go  阿里巴巴开源移动容器化框架Atlas的技术演进之路
  下一篇:go  一场变美盛宴后面的大数据故事