栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

数据类型转换

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据类型转换

  1. 由低到高

    byte,short,char ----> int ----> long ----->float -----> double

  2. 运算顺序

    先转换类型,再计算

  3. 计算规则

    由高到低,需要强制转换;由低到高,自动转换

public class Demo1 {
    public static void main(String[] args) {
        int i = 128;
        //强制转换
        byte j = (byte)i;//byte最大为127  内存溢出
        double k = i;

        System.out.println(i);
        System.out.println(j);
        System.out.println(k);

        

        System.out.println((int)23.7);
        System.out.println((int)-23.79f);//-23  精度

        char c = 'a';
        int d = c+1;
        System.out.println(d);
        System.out.println((char)d);

    }
}
输出结果
128
-128
128.0
23
-23
98
b

注意计算顺序,先换类型,后计算

有时候要注意内存溢出问题

public class Demo2 {
    public static void main(String[] args) {
        //操作数较大时,注意溢出问题
        int money = 10_0000_0000;
        int years = 20;
        int total = money * years;
        long total2 = money * years;
        long total3 = money * (long)years;
        System.out.println(total);
        System.out.println(total2);
        System.out.println(total3);
    }
}

输出结果

-1474836480
-1474836480
20000000000

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/684651.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号