• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

秃头小白cxy

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

Java类型转换

public class Demo02 {
    public static void main(String[] args) {
        int i = 128;
        byte b =(byte)i; //值超出范围(内存溢出)
        //强制转换 (类型)变量名  高转低
        //自动转换  低到高
        System.out.println(i); //128
        System.out.println(b); //-128
        /*
        注意:
        1.不能对布尔值进行转换
        2.不能把对象类型转换为不相干的类型
        3.把高容量转低容量的时候,强制转换
        4.转换的时候可能存在内存溢出,或者精度问题
         */
        System.out.println("==============");
        System.out.println((int)66.6); //66
        System.out.println((int)-66.666F); //-66

        System.out.println("============== ");
        char c = 'a';
        int d = c+1;
        System.out.println(d);  //98
        System.out.println((char) d); //b 编码b=98

        // 操作比较大的数据的时候,注意溢出问题
        //数字之间可以用下划线分割
        int money = 10_0000_0000;
        int years = 20;
        int total = money*years;
        long total2=money*years;
        System.out.println(total); //-1474836480 计算的时候溢出了
        System.out.println(total2); //-1474836480 默认是int,转换之前已将存在问题了

        long total3 = money*((long)years); //先把一个数转换为long
        System.out.println(total3); //20000000000
        //我们在用long的时候,因为小写的l和数字1比较像,所以L尽量大写
    }
}

posted on 2021-04-20 15:03  秃头小白cxy  阅读(32)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3