gpt4 book ai didi

java - int 的基本算术运算 - Java

转载 作者:搜寻专家 更新时间:2023-10-30 21:02:51 25 4
gpt4 key购买 nike

我最近注意到 Java 关于 Java 中基本算术运算的特性。用下面的代码

byte a = 3;
byte b = 4;
byte c = a * b;

我收到“类型不匹配”编译错误...

Java中的基本算术运算(+-*/)只对primitive进行int 和高阶数据类型(longdouble 等),而 byteshort 首先转换为 int 然后计算?

最佳答案

bytecharshort 的操作被扩展为 int,除非编译器可以确定该值是在范围内。

final byte a = 3, b = 4;
byte c = a * b; // compiles

final byte a = 3, b = 40;
byte c = a * b; // compiles

final int a = 3, b = 4;
byte c = a * b; // compiles !!

但是

byte a = 3, b = 4;
byte c = a * b; // doesn't compile as the result of this will be `int` at runtime.

final byte a = 30, b = 40;
byte c = a * b; // doesn't compile as the value is too large, will be an `int`

顺便说一句,即使它导致溢出,也会编译。 :]

final int a = 300000, b = 400000;
int c = a * b; // compiles but overflows, is not made a `long`

关于java - int 的基本算术运算 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14125843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com