Java基本数据类型转化总结


Java语言支持的数据类型分为两类:基本类型和引用类型。包含8种基本数据类型。


(1)boolean类型不可以转换为其他的数据类型。

(2)整形、字符型、浮点型的数据在混合运算中相互转化时,转化遵循如下规则:

1)容量小的类型自动转化成容量大的类型,数据类型按照容量大小排序为:

       byte、short、char->int->long->foat->double

       byte、short、char之间不可以相互转化,他们三者在计算时,首先转化成int。

可以用下图表示转化关系:


2)容量大的类型转化成容量小的类型时,要加上强制转换符,但可能造成精度降低或溢出,使用时要格外注意。

3)有多钟类型的混合计算时,系统首先将所有的数据转换成容量最大的数据类型,然后再进行计算。

4)实数常量默认为double,例如:1.2。

4)整数常量默认为int,例如:123。

下面是一些例子:

public class Test {  
          
     public static void method() {  
          
        int i = 1,j;  
        float f1 = 0.1f;//必须加f 默认double  
        float f2 = 123;  
        long ll = 12345678;  
        long l2 = 8888888888L;//必须加L int 放不下  
        double d1 = 2e20,d2 = 124;  
        byte b1 =1;  
        byte b2 = 2;  
    //  byte b3 = 129;//大于 127 出错  
    //  j = j+10;//错误 j 没有值  
        i = i/10;  
        i =(int)(i*0.1);//0.1是double 结果为double doube赋值给int  需要强制转化  
        char c1 = 'a',c2 = 125;  
        //byte b = b1 - b2;//b1 b2计算需要先转化成int 计算结果为int int 赋值给byte 出错  
        //char c = c1 + c2 - 1;//int 赋值给char 出错  
        float f3 = f1 + f2;  
        float f4 =(float)(f1 + f2*0.1);//计算结果为doube 需要强制转化  
        j = 0;  
        double d = d1*i +j;  
        float f = (float)(d1*5+d2);  
        }  
     
    public static void main(String args[]) { 
        	
        method();     
        int i1 = 123;  
        int i2 = 456;  
        double d1 = (i1+i2)*1.2;//i1 i2为int 类型 计算时,系统转化为double型计算  
        float f1=(float)((i1+i2)*1.2);//1.2默认为double 计算结果为double 强制类型转化为float  
        byte b1 = 1;  
        byte b2 = 2;  
        byte b3 = (byte)(b1+b2);//系统将转换为int型运算,需要强制转化运算符  
      
        double d2 = 1e200;  
        float f2 = (float)d2;//会产生溢出  
        System.out.println(f2);//注意结果是无穷 浮点数 有小数点 内存存放形式导致  
          
        byte b4 = 67;  
        byte b5 = 89;  
        byte b6 = (byte)(b4+b5);//会产生溢出  
        System.out.println(b6);//会截断 留下一个字节  
          
      
        float f3 = 1.23f;//必须加f  
        long ll = 123;  
        long l2 = 300000000001L;//必须加L,因为默认int类型   
        float f = ll + l2 + f3;//系统将转化为float计算  
        long l = (long)f;//强制转化会舍去小数部分(不是四舍五入)  
        System.out.println(l);  
      
        }  
          
    }  



猜你喜欢

转载自blog.csdn.net/dyingfair/article/details/51973057
今日推荐