Java numeric type conversion

7 in the Java language provides numeric type can be converted to each other, there are two types of conversion: automatic conversion and casts;

Small table range may be greater number to the number of automatic conversion table range, automatic conversion is as follows:

FIG automatic conversion

Respectively, in the code shows automatic conversion and casts, and the character string into basic types:

public class TypeConversion 
{
    public static void main(String[] args) 
    {
        /**
        * 自动类型转换
        */
        //int类型可以自动转换为float类型
        int a = 6;
        float b = a;

        //byte类型不能自动转换为char类型,可以自动转换为double类型
        byte c = 1;
        //char d = c;
        double f = c;

        //基本类型的值和字符串进行连接运算时,基本类型的值自动转换为字符串类型
        String str = 3.5f + "";
        System.out.println(str);//结果为3.5f
        System.out.println(3 + 4 + "Hello");//结果为 7Hello
        System.out.println("Hello" + 3 + 4);//结果为 Hello34

        /**
        * 强制类型转换
        * 强制转换过程中,把大范围类型转换为小范围类型时容易出现溢出
        * 浮点数转int类型时,直接截断浮点数的小数点部分
        * 32位的int转8位byte时,直接截断前24位,只留后8位
        */
        //强制把int类型的值转换为byte类型,double类型强制转换为int类型
        int iValue = 95;
        byte bValue = (byte)iValue;
        double dValue = 7777.98;
        int tol = (int)dValue;
        System.out.println(bValue);
        System.out.println(tol);

        String a = "45";
        //Java为8种基本类型提供了包装类,boolean--Boolean,byte--Byte,short--Short,int--Integer,long--Long,char--Character,float--Float,double--Double
        //parseXxx(String str)静态方法用于将字符串转换成基本类型
        int tal = Integer.paresInt(a);

        /**
        * 表达式类型的自动提升
        * 所有的byte类型、short类型、char类型将被提升到int类型
        * 整个算术表达式的类型自动提升到与表达式中最高等级操作数同样的类型
        */
        short sValue = 5;
        //表达式中的sValue将自动提升到int类型,右边表达式的类型为int
        //将一个int类型的值赋值给short类型的变量将发生错误
        //sValue = sValue - 2;

        byte bb = 32;
        char cc = 4;
        int ii = 3;
        double dd = .314;
        //两边都是double类型,正确
        double result = bb + cc + ii * dd;


    }
}


Guess you like

Origin www.cnblogs.com/afar-blog/p/11978525.html