java类型转换

Java数据类型

一、基本数据类型

八种基本数据类型

整型:byte/short/int/long

浮点型:float/double

字符型:char

布尔型:boolean

二、引用数据类型

类:class

接口:interface

数组:array

类型转换

前提:讨论的不包含boolean型,java中不会等于0/1.

一、自动类型转换

超过范围,编译不通过

在这里插入图片描述

低字节向高字节会自动转换:

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

byte, short, char三者运算为int(也包括同种类型之间运算)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Q2IoswqG-1687324441905)(/Users/xuhanqi/Library/Application Support/typora-user-images/image-20230621125359407.png)]

二、强制类型转换

高位截断,可能会损失精度

public class VariableTest3 {
    public static void main(String[] args) {
        double d1 = 150.12;

        int i1 = (int)d1;
        System.out.println(i1);

        int i2 = 128;
        byte b1 = (byte) i2;
        System.out.println(b1);	// 输出-128
    }
}

可能的错误

public class VariableTest4 {
    public static void main(String[] args) {
        // 过大的整数,整数默认为int型,超出范围
        long l1 = 12333333333;  // 编译不通过
        long l2 = 12333333333L;

        // 浮点默认为double型
        float f1 = 12.13; // 编译不通过
        float f2 = 12.13f;

        byte b = 12;
        byte b1 = b + 1; // 编译不通过
        float f3 = b + 12.3; // 编译不通过
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值