简体   繁体   English

在 java 中,long 到 int 和 int 到 short 的类型转换工作方式不同

[英]type casting works differently for long to int and int to short in java

  1. short t=(short)1 * 3;
  2.  int tadpole = (int)5 * 2L;

First statement works perfectly fine, But second throws compilation error.第一条语句工作得很好,但第二条语句抛出编译错误。 According to the rules, when performing arithmetic operations, if any byte/short/char will be converted to int by default.按照规则,在进行算术运算时,如果有byte/short/char,默认都会转为int。 So how is first expression working?那么第一个表达式是如何工作的呢?

also, I checked for另外,我检查了

  1. short x = (int) 30;
  2.  int y = (long) 30;

statement 3 works, but statement 4 doesn't work.语句 3 有效,但语句 4 无效。

Why can I assign an int to a short , but not long to int ?为什么我可以将int分配给short而不是long分配给int

The answer is in section 5.2 Assignment Conversion of the JLS :答案在第5.2 节 JLS 的赋值转换中

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:此外,如果表达式是 byte、short、char 或 int 类型的常量表达式 (§15.28):

  • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.如果变量的类型是 byte、short 或 char,并且常量表达式的值可以用变量的类型表示,则可以使用收缩原始转换。

Your examples 1 and 3 fall under this clause: these are constant expressions (with a value of 3 or 30), the type of the expression is int and the values fit into a short .您的示例 1 和 3 属于此子句:这些是常量表达式(值为 3 或 30),表达式的类型为int并且值适合short

There is no similar clause for constant expressions with long values.对于具有long值的常量表达式,没有类似的子句。

Your examples 2 and 4 produce long values (in example 2 because one of the operands is long , in example 4 because of the cast to long ).您的示例 2 和 4 产生long值(在示例 2 中是因为其中一个操作数是long ,在示例 4 中是因为转换为long )。


Please note that your examples 1 and 2 are probably not interpreted as you might think they are.请注意,您的示例 1 和 2 可能未按照您认为的那样进行解释。 Casting has higher precedence than multiplication and therefore the examples are evaluated as if they were written as:转换的优先级高于乘法,因此示例的计算就像它们被写成:

  1.  short t = ((short)1) * 3;
  2.  int tadpole = ((int)5) * 2L;

Why does this rule exist?为什么存在这条规则?

One of the reasons is the definition of Integer Literals : any time the source code contains an integer number (without the suffix l or L which would make it a long ) the type of that literal is int .原因之一是Integer 字面量的定义:任何时候源代码包含 integer 数字(没有后缀lL ,这会使它成为long ),该字面量的类型是int

The rule from "Assignment Conversion" means that you can write “赋值转换”中的规则意味着你可以写

byte[] data = { 1, 2, 3, 4 };

Without that rule, you would have to write没有这条规则,你将不得不写

byte[] data = { (byte) 1, (byte) 2, (byte) 3, (byte) 4 };

There is no need for a similar rule for long constants. long常量不需要类似的规则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM