java数据类型转换

类型转换

规则

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

低-------------------------------------------------------->高

运算中,不同类型的数据要先转换为统一数据,再运算

  int i = 128;
        byte b = (byte) i;
        double d = i;

        //强制转换   (类型)变量名    高--低
        //自动转换     低--高

        System.out.println(i);  //128
        System.out.println(b);  //-128,内存溢出,  byte最大到127
        System.out.println(d);

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LbKu4DwP-1617787708940)(C:\Users\tiant\Pictures\Saved Pictures\屏幕截图 2021-04-07 170420.png)]

注意点

  • 不能对布尔值进行转换
  • 不能转换对象为不相干类型
  • 高容量转换为低容量时,强制转换;低容量转换为高容量时,自动转换
  • 转换时可能出现内存溢出或精度问题
  • 注意类型默认问题

精度和Unicode转换

System.out.println((int)23.4);  //23
System.out.println((int)-45.23f);   //-45
//精度

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

在这里插入图片描述

默认数据类型

public class Demo6 {
    public static void main(String[] args) {
        //操作的较大数时,注意溢出问题
        //JDK7新特性,数字间用下划线分割
        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
        long total3 = money*((long)years);
        System.out.println(total3);     //20000000000

    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值