Chinaunix首页 | 论坛 | 博客
  • 博客访问: 457134
  • 博文数量: 153
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1575
  • 用 户 组: 普通用户
  • 注册时间: 2016-12-20 17:02
文章分类

全部博文(153)

文章存档

2017年(111)

2016年(42)

我的朋友

分类: Java

2017-05-24 15:59:50

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变量的申明及使用.

阅读(1632) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~