java基础之数据类型转换

一 简介

1.Java是强类型语言,所以要进行有些运算的时候,需要用到类型转换。

由低到高:

byte,short,char——int——long——float——double

二 转换类型

1.强制转换

由高到低 (类型)变量名

 int a=10;
        byte b=(byte)a;
        double c=12.1;
        int d=(int)c;//强制转换
        System.out.println(b);
        System.out.println(d);
10
12

Process finished with exit code 0

2.自动转换

由低到高

 int f=10;
        double g=f;//自动转换,因为double为浮点类型,所以输出结果有小数
        char t='a';
        int o=t+1;
        System.out.println(g);
        System.out.println(o);



================
10.0
98

三 注意点

1.不能对布尔类型进行转换。

2.不能把对象类型转换为不相干的类型。

3.把高容量转换到低容量的时候,强制转换。

4.转换的时候可能存在内存溢出或精度问题。

 double h=9.9999;                                           
 long l=(long)h;                                            
 float p=9.999999F;                                         
 int x=(int)p;//由浮点类型转换为整数类型,运算由精度问题,小数位丢失                  
 System.out.println(l);                                     
 System.out.println(x);                                     
 System.out.println((int)24.99);//精度问题                      
 System.out.println((long)88.8);                            

=====================
9
9
24
88
===================

 

int money=10_0000_0000;//数据之间可以用下划线进行分割,输出结果不变
        int years=20;
        int total=money*years;//操作比较大,输出结果溢出,需进行高级类型转换
        System.out.println(total);
    }
=====================
-1474836480
 int money=10_0000_0000;//数据之间可以用下划线进行分割,输出结果不变                               
 int years=20;                                                                
 int total=money*years;//操作比较大,输出结果溢出,需进行高级类型转换                               
 System.out.println((long)total); //上述操作已经把total定义为int,结果转化为long也是默认int型,转化失败 
===================
-1474836480
 System.out.println((long)money*years);                           
 System.out.println(money*(long)years);                           
 System.out.println((long)years*money);//需要输出结果时,在任意元素值前加上long进行转换
=============================
20000000000
20000000000
20000000000

2022-12-07 10:44:57

posted @ 2022-12-07 10:45  努力的小白07  阅读(80)  评论(0)    收藏  举报