第一章04-类型转换

类型转换

  • 由于Java是强语言类型,所以要进行有些运算的时候,需要用到类型转换
低 --------------------------------------> 高(字节)

byte,short,char-> int-> long-> float-> double
  • 运算中,不同类型的数据先转化为同一类型,然后进行运算。
  • 强制类型转换
  • 自动类型转换

测试

public class demo4 {
    public static void main(String[] args) {
        int i = 128;
        byte b = (byte)i;// -128
        //强制转换 (类型)变量名 高--低;
        //自动转换 低--高;
        System.out.println(i);
        System.out.println(b);

        /*
        注意点:
        1.不能对布尔值进行转换;
        2.不能把对象类型转换为不相干的类型;
        3.在把高容量转换到低容量的时候,强制转换;
        4转换的时候可能存在内存溢出,或者精度问题!
         */
        System.out.println("===========================");
        System.out.println((int)23.7);
        System.out.println((int)-45.89F);

        System.out.println("===========================");
        char c ='a';
        int d = c+1;
        System.out.println(d);//输出98
        System.out.println((char)d);


    }
}

输出:

128
-128
===========================
23
-45
===========================
98
b

测试:

public class demo06 {
    public static void main(String[] args) {
        //操作比较大的数时,注意溢出问题;
        //JDK7 新特性,数字之间可以用下滑键分割;
        int money = 10_0000_0000;
        //System.out.println(money);
        int years = 20;
        int total = money*years;//溢出
        long total2 = money*years;//默认是int ,转换之前已经出问题了;
        System.out.println(total);//-1474836480
        System.out.println(total2);//还是-1474836480
        long total3 = money*(long)years;
        System.out.println(total3);//200_0000_0000
        //  L  l容易被看成1,最好大写
    }
}

输出:

-1474836480
-1474836480
20000000000
posted @   DaoShl  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示