Java 基础 之 常量类型转换

http://www.verejava.com/?id=16992572054911

/*
类型转换分为以下几种情况
1. 整型类型转换 
2. 浮点类型转换
3. 布尔类型转换
4. 字符类型转换
*/
public class TypeConvert
{
    public static void main(String[] args)
    {
        byte a1=1;
        int  b1=2;
        //小整数类型转换成大整数类型, 直接转换
        b1=a1;
        System.out.println(b1);

        byte a2=1;
        int  b2=2;
        int  b3=128;
        //大整数类型转换成小整数类型, 需要强制类型转换, 并且可能损失精度. 将会把高位切除.
        a2=(byte)b2;
        a2=(byte)b3;
        System.out.println(a2);

        byte    c1=1;
        float   c2=10.3f;
        //整数转浮点型,直接转换
        c2=c1;
        System.out.println(c2);

        byte    d1=1;
        float   d2=10.3f;
        float   d3=128.2f;
        //浮点类型转整型 直接去掉小数部分, 需要强制类型转换, 并且可能丢失精度
        d1=(byte)d2;
        d1=(byte)d3;
        System.out.println(d1);

        //布尔类型不能转换成其他类型, 其他类型也不能转换成布尔类型
        boolean e1=true;
        //e1=(boolean)1;

        char    f1='a';
        int     f2=1;
        char    f3='b';
        int     f4='b'+1;
        char    f5='b'+1;
        //整型可以转换成 字符类型,需要强制类型转换,整型也可以转换成字符型,转换的规则为 ACSII 码表
        f1=(char)f2;
        f2=f3;
        System.out.println(f1);
        System.out.println(f2);
        System.out.println(f4);
        System.out.println(f5);

        //字符串连接 + 转换
        String str="hello";
        String str2=str+1;
        String str3=str+2.5;
        String str4=str+true;
        String str5=str+'F';
        //字符串跟其他基本类型相加  其他类型自动转换成字符串连接
        System.out.println(str2);
        System.out.println(str3);
        System.out.println(str4);
        System.out.println(str5);
    }
}
/*
总结:
    1. 类型转换小数值到大数值转换 byte<short<int<float<long<double
    2. 整型 默认是 int 型, 浮点型 默认是 double 型
*/

http://www.verejava.com/?id=16992572054911

猜你喜欢

转载自www.cnblogs.com/verejava/p/9183858.html