Java 整数到短的转换规则
Posted
技术标签:
【中文标题】Java 整数到短的转换规则【英文标题】:Java integer to short conversion rules 【发布时间】:2020-07-30 16:20:37 【问题描述】:在代码中,只有第一种情况(整数变量到 short)有编译错误(从 int 到 short 的有损转换)。为什么其他情况(整数文字转短,最终整数变量转短)没有同样的编译错误?
public class Test
public static void main(String[] args)
short shortNum = 0;
//integer variable to short
int intNum = 12;
shortNum = intNum;
//integer literal to short
shortNum = 12;
//final integer variable to short
final int finalNum = 12;
shortNum = finalNum;
【问题讨论】:
编译器可以看到常量值12
适合一个short。
【参考方案1】:
将答案视为 cmets:
short shortNum = 0;
//integer variable to short
int intNum = 12;
shortNum = intNum; //doesn't work, because casting primitives is required any time you are going from a larger numerical data type to a smaller numerical data type.
//integer literal to short
shortNum = 12; //This is not integer literal per se, you're initializing your short variable with 12, which fits in short data type, so it's short.
//final integer variable to short
final int finalNum = 12; //your variable is final, and according to Java Language Specification, if final variable's value fits into the type you're casting it, then no explicit cast is needed.
shortNum = finalNum;
【讨论】:
还要注意byte
、short
和char
数据类型在与算术运算符一起使用时有一个棘手的部分。例如short x = 2; short y = 3; short z = x + y;
将无法编译,因为结果被提升为int
这可以这样表达:From OCA Java SE 8 Book: short values are automatically promoted to int when applying any arithmetic operator, with the resulting value being of type int.
【参考方案2】:
答案在这篇文章中:Type cast issue from int to byte using final keyword in java。
如果 Java 知道该数字是一个常量并且适合另一种类型,那么您可以使用它。
在非常量值的情况下,你无法知道变量将如何演变......在这种情况下,为了保护,它不会允许类型更改。
【讨论】:
以上是关于Java 整数到短的转换规则的主要内容,如果未能解决你的问题,请参考以下文章
如何将整数转换为 Python 中最短的 url 安全字符串?