基元类型“短”- Java中的强制转换

时间:2022-02-10 16:35:38

I have a question about the primitive type short in Java. I am using JDK 1.6.

我有一个关于Java中短的原始类型的问题。我正在使用JDK 1.6。

If I have the following:

如果我有以下几点:

short a = 2;
short b = 3;
short c = a + b;

the compiler does not want to compile - it says that it "cannot convert from int to short" and suggests that I make a cast to short, so this:

编译器不希望编译—它说它“不能将int转换为short”,并建议我将cast转换为short,因此:

short c = (short) (a + b);

really works. But my question is why do I need to cast? The values of a and b are in the range of short - the range of short values is {-32,768, 32767}. I also need to cast when I want to perform the operations -, *, / (I haven't checked for others).

确实有效。但我的问题是,为什么我需要施放?a和b的值都在short - short值的范围是{-32,768,32767}。当我想执行操作-,*,/(我还没有检查其他操作)时,我也需要进行cast。

If I do the same for primitive type int, I do not need to cast aa+bb to int. The following works fine:

如果我对原始类型int做同样的处理,我不需要将aa+bb投射到int。

int aa = 2;
int bb = 3;
int cc = aa +bb;

I discovered this while designing a class where I needed to add two variables of type short, and the compiler wanted me to make a cast. If I do this with two variables of type int, I don't need to cast.

我在设计一个需要添加两个类型为short的变量的类时发现了这一点,编译器希望我进行强制转换。如果我对两个类型为int的变量执行此操作,我不需要强制转换。

A small remark: the same thing also happens with the primitive type byte. So, this works:

一个小注释:同样的事情也发生在原始类型字节上。所以,这工作原理:

byte a = 2;
byte b = 3;
byte c = (byte) (a + b);

but this not:

但这不是:

byte a = 2;
byte b = 3;
byte c = a + b;

For long, float, double, and int, there is no need to cast. Only for short and byte values.

对于长、浮动、双、int,不需要强制转换。只适用于短的和字节的值。

10 个解决方案

#1


57  

As explained in short C# (but also for other language compilers as well, like Java)

正如c#中所解释的那样(但对于其他语言编译器,比如Java)

There is a predefined implicit conversion from short to int, long, float, double, or decimal.

有一个预定义的隐式转换,从短到整数,长,浮点,双,或十进制。

You cannot implicitly convert nonliteral numeric types of larger storage size to short (see Integral Types Table for the storage sizes of integral types). Consider, for example, the following two short variables x and y:

您不能隐式地将更大存储空间的非文字数字类型转换为短的(请参见整数类型表,以存储集成类型的存储大小)。例如,考虑以下两个短变量x和y:

short x = 5, y = 12;

The following assignment statement will produce a compilation error, because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

下面的赋值语句将产生编译错误,因为赋值操作符右边的算术表达式默认地计算为int。

short z = x + y;   // Error: no conversion from int to short

To fix this problem, use a cast:

要解决这个问题,请使用cast:

short z = (short)(x + y);   // OK: explicit conversion

It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:

可以使用以下语句,其中目标变量具有相同的存储大小或更大的存储大小:

int m = x + y;
long n = x + y;

A good follow-up question is:

一个很好的后续问题是:

"why arithmetic expression on the right-hand side of the assignment operator evaluates to int by default" ?

为什么赋值运算符右边的算术表达式默认值为int ?

A first answer can be found in:

第一个答案可以在:

Classifying and Formally Verifying Integer Constant Folding

分类和正式验证整数常数折叠

The Java language specification defines exactly how integer numbers are represented and how integer arithmetic expressions are to be evaluated. This is an important property of Java as this programming language has been designed to be used in distributed applications on the Internet. A Java program is required to produce the same result independently of the target machine executing it.

Java语言规范确切地定义了如何表示整数,以及如何计算整数算术表达式。这是Java的一个重要属性,因为这种编程语言已经被设计用于Internet上的分布式应用程序。Java程序需要独立于执行它的目标机器生成相同的结果。

In contrast, C (and the majority of widely-used imperative and object-oriented programming languages) is more sloppy and leaves many important characteristics open. The intention behind this inaccurate language specification is clear. The same C programs are supposed to run on a 16-bit, 32-bit, or even 64-bit architecture by instantiating the integer arithmetics of the source programs with the arithmetic operations built-in in the target processor. This leads to much more efficient code because it can use the available machine operations directly. As long as the integer computations deal only with numbers being “sufficiently small”, no inconsistencies will arise.

与之相反,C(以及大多数广泛使用的命令式和面向对象编程语言)则更加松散,并且开放了许多重要的特性。这种不准确的语言规范背后的意图是明确的。相同的C程序应该在16位、32位甚至64位的体系结构上运行,方法是实例化源程序的整数算术,并在目标处理器中内置算术操作。这将导致更高效的代码,因为它可以直接使用可用的机器操作。只要整数计算只处理“足够小”的数字,就不会出现不一致。

In this sense, the C integer arithmetic is a placeholder which is not defined exactly by the programming language specification but is only completely instantiated by determining the target machine.

从这个意义上说,C整数算法是一个占位符,它不是由编程语言规范定义的,而是通过确定目标机器来完全实例化的。

Java precisely defines how integers are represented and how integer arithmetic is to be computed.

Java精确地定义了整数是如何表示的,以及如何计算整数运算。

      Java Integers
--------------------------
Signed         |  Unsigned
--------------------------
long  (64-bit) |
int   (32-bit) |
short (16-bit) |  char (16-bit)
byte  (8-bit)  |

Char is the only unsigned integer type. Its values represent Unicode characters, from \u0000 to \uffff, i.e. from 0 to 216−1.

Char是惟一的无符号整数类型。其值表示Unicode字符,从\ \ uffff u0000,即从0到216−1。

If an integer operator has an operand of type long, then the other operand is also converted to type long. Otherwise the operation is performed on operands of type int, if necessary shorter operands are converted into int. The conversion rules are exactly specified.

如果一个整数运算符有一个类型为long的操作数,那么另一个操作数也被转换为long类型。否则,操作将在类型为int的操作数上执行,如果需要,将更短的操作数转换为int。

[From Electronic Notes in Theoretical Computer Science 82 No. 2 (2003)
Blesner-Blech-COCV 2003: Sabine GLESNER, Jan Olaf BLECH,
Fakultät für Informatik,
Universität Karlsruhe
Karlsruhe, Germany]

[摘自《理论计算机科学电子注释》第82期(2003):Blesner-Blech-COCV 2003: Sabine GLESNER, Jan Olaf BLECH, Fakultat fur Informatik, Universitat Karlsruhe Karlsruhe, Germany]

#2


17  

EDIT: Okay, now we know it's Java...

编辑:好的,现在我们知道是Java…

Section 4.2.2 of the Java Language Specification states:

Java语言规范的4.2.2节:

The Java programming language provides a number of operators that act on integral values:

Java编程语言提供了许多操作符,它们作用于整数值:

[...]

[…]

  • The numerical operators, which result in a value of type int or long:
  • 数值运算符,导致类型为int或long:
  • [...]
  • […]
  • The additive operators + and - (§15.18)

  • 加法运算符+和-(§15.18)
  • In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int or long, which is why you need to cast to assign to a short variable.

    换句话说,它就像c#——加法运算符(当应用到整数类型时)只会导致int或long,这就是为什么需要对短变量进行赋值。

    Original answer (C#)

    原始答案(c#)

    In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:

    在c#(您还没有指定语言,所以我猜)中,基本类型上唯一的加法运算符是:

    int operator +(int x, int y);
    uint operator +(uint x, uint y);
    long operator +(long x, long y);
    ulong operator +(ulong x, ulong y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:

    这些在c# 3.0规范7.7.4中。此外,定义了十进制加法:

    decimal operator +(decimal x, decimal y);
    

    (Enumeration addition, string concatenation and delegate combination are also defined there.)

    (这里还定义了枚举添加、字符串连接和委托组合。)

    As you can see, there's no short operator +(short x, short y) operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.

    如您所见,没有短操作符+(短x,短y)操作符——因此两个操作数都隐式地转换为int,并使用int形式。这意味着结果是“int”类型的表达式,因此需要强制转换。

    #3


    16  

    In C# and Java, the arithmatic expression on the right hand side of the assignment evaluates to int by default. That's why you need to cast back to a short, because there is no implicit conversion form int to short, for obvious reasons.

    在c#和Java中,赋值右边的算术表达式默认值为int。这就是为什么您需要返回到一个short,因为由于明显的原因,不存在从int到short的隐式转换。

    #4


    6  

    Given that the "why int by default" question hasn't been answered ...

    既然“为什么int默认”问题还没有得到回答……

    First, "default" is not really the right term (although close enough). As noted by VonC, an expression composed of ints and longs will have a long result. And an operation consisting of ints/logs and doubles will have a double result. The compiler promotes the terms of an expression to whatever type provides a greater range and/or precision in the result (floating point types are presumed to have greater range and precision than integral, although you do lose precision converting large longs to double).

    首先,“违约”并不是真正正确的术语(尽管已经足够接近了)。正如VonC所指出的,一个由int和long组成的表达式将会产生很长的结果。而由ints/log和double组成的操作将产生双重结果。编译器将表达式的术语推广到任何类型,从而在结果中提供更大的范围和/或精度(假定浮点类型具有比整数更大的范围和精度,尽管您确实会丢失将大长转换为双长的精度)。

    One caveat is that this promotion happens only for the terms that need it. So in the following example, the subexpression 5/4 uses only integral values and is performed using integer math, even though the overall expression involves a double. The result isn't what you might expect...

    有一点需要注意的是,这种提升只会发生在需要它的条件下。因此,在下面的示例中,子表达式5/4只使用整数值,并使用整数math执行,即使整个表达式包含一个double。结果并不像你想象的那样……

    (5/4) * 1000.0
    

    OK, so why are byte and short promoted to int? Without any references to back me up, it's due to practicality: there are a limited number of bytecodes.

    为什么字节和短字节被提升为int?没有任何引用来支持我,这是由于实用性:字节码的数量是有限的。

    "Bytecode," as its name implies, uses a single byte to specify an operation. For example iadd, which adds two ints. Currently, 205 opcodes are defined, and integer math takes 18 for each type (ie, 36 total between integer and long), not counting conversion operators.

    “字节码”,顾名思义,使用一个字节来指定操作。例如iadd,它添加了两个ints。目前,已经定义了205个操作码,每种类型的整型数都需要18个(即,整型和长型之间总共36个操作码),不包括转换操作符。

    If short, and byte each got their own set of opcodes, you'd be at 241, limiting the ability of the JVM to expand. As I said, no references to back me up on this, but I suspect that Gosling et al said "how often do people actually use shorts?" On the other hand, promoting byte to int leads to this not-so-wonderful effect (the expected answer is 96, the actual is -16):

    如果每个字节都有自己的一组操作码,那么您的操作码是241,这限制了JVM扩展的能力。就像我说的,没有人支持我的观点,但我怀疑高斯林等人说过“人们到底有多经常穿短裤?”另一方面,将字节提升为int会导致这种不太妙的效果(预期答案是96,实际答案是-16):

    byte x = (byte)0xC0;
    System.out.println(x >> 2);
    

    #5


    5  

    What language are you using?

    你用什么语言?

    Many C based languages have a rule that any mathematical expression is performed in size int or larger. Because of this, once you add two shorts the result is of type int. This causes the need for a cast.

    许多基于C的语言都有一个规则,即任何数学表达式的大小都是整数或整数。正因为如此,一旦你加了两条短裤,结果就是int型的,这就造成了对演员的需求。

    #6


    2  

    Java always uses at least 32 bit values for calculations. This is due to the 32-bit architecture which was common 1995 when java was introduced. The register size in the CPU was 32 bit and the arithmetic logic unit accepted 2 numbers of the length of a cpu register. So the cpus were optimized for such values.

    Java总是使用至少32位值进行计算。这是由于32位架构,这在java引入时是很常见的。CPU中的寄存器大小为32位,算术逻辑单元接受两个CPU寄存器长度的数字。因此,我们对cpu进行了优化。

    This is the reason why all datatypes which support arithmetic opperations and have less than 32-bits are converted to int (32 bit) as soon as you use them for calculations.

    这就是为什么所有支持算术运算并且小于32位的数据类型在您使用它们进行计算时都被转换为int(32位)的原因。

    So to sum up it mainly was due to performance issues and is kept nowadays for compatibility.

    综上所述,它主要是由于性能问题而保留至今的兼容性。

    #7


    1  

    In java, every numeric expression like:

    在java中,每个数值表达式:

    anyPrimitive zas = 1;
    anyPrimitive bar = 3;
    ?? x = zas  + bar 
    

    x will always result to be at least an int, or a long if one of the addition elements was a long.

    x总是至少是一个int数,或者如果其中一个相加元素是长的话,则是一个long。

    But there's are some quirks tough

    但也有一些奇怪的事情

    byte a = 1; // 1 is an int, but it won't compile if you use a variable
    a += 2; // the shortcut works even when 2 is an int
    a++; // the post and pre increment operator work
    

    #8


    1  

    AFAIS, nobody mentions of final usage for that. If you modify your last example and define variables a and b as final variables, then the compiler is assured that their sum, value 5 , can be assigned to a variable of type byte, without any loss of precision. In this case, the compiler is good to assign the sum of a and b to c . Here’s the modified code:

    没有人提到它的最终用法。如果修改上一个示例并将变量a和b定义为最终变量,那么编译器将确保它们的总和(值5)可以分配给类型为byte的变量,而不会丢失任何精度。在这种情况下,编译器最好将a和b的和赋给c。这是修改后的代码:

    final byte a = 2;
    final byte b = 3;
    byte c = a + b;
    

    #9


    1  

    Any data type which is lower than "int" (except Boolean) is implicitly converts to "int".

    任何小于“int”(布尔值除外)的数据类型都隐式地转换为“int”。

    In your case:

    在你的例子:

    short a = 2;
    short b = 3;
    short c = a + b;
    

    The result of (a+b) is implicitly converted to an int. And now you are assigning it to "short".So that you are getting the error.

    (a+b)的结果隐式地转换为int,现在将其赋值为“short”。这样就得到了误差。

    short,byte,char --for all these we will get same error.

    短,字节,字符——对于所有这些,我们会得到相同的错误。

    #10


    0  

    I'd like to add something that hasn't been pointed out. Java doesn't take into account the values you have given the variables (2 and 3) in...

    我想补充一些没有指出的东西。Java没有考虑您在…中给变量(2和3)的值。

    short a = 2; short b = 3; short c = a + b;

    短= 2;短b = 3;短c = a + b;

    So as far as Java knows, you could done this...

    就Java所知,您可以这样做……

    short a = 32767; short b = 32767; short c = a + b;

    短= 32767;短b = 32767;短c = a + b;

    Which would be outside the range of short, it autoboxes the result to an int becuase it's "possible" that the result will be more than a short but not more than an int. Int was chosen as a "default" because basically most people wont be hard coding values above 2,147,483,647 or below -2,147,483,648

    这将是短的范围之外,它autoboxes结果int因为“可能的”,结果将是一个多短但不超过一个int,int基本上被选为“默认”,因为大多数人不会硬编码值高于2147483647或-2147483648以下吗

    #1


    57  

    As explained in short C# (but also for other language compilers as well, like Java)

    正如c#中所解释的那样(但对于其他语言编译器,比如Java)

    There is a predefined implicit conversion from short to int, long, float, double, or decimal.

    有一个预定义的隐式转换,从短到整数,长,浮点,双,或十进制。

    You cannot implicitly convert nonliteral numeric types of larger storage size to short (see Integral Types Table for the storage sizes of integral types). Consider, for example, the following two short variables x and y:

    您不能隐式地将更大存储空间的非文字数字类型转换为短的(请参见整数类型表,以存储集成类型的存储大小)。例如,考虑以下两个短变量x和y:

    short x = 5, y = 12;
    

    The following assignment statement will produce a compilation error, because the arithmetic expression on the right-hand side of the assignment operator evaluates to int by default.

    下面的赋值语句将产生编译错误,因为赋值操作符右边的算术表达式默认地计算为int。

    short z = x + y;   // Error: no conversion from int to short
    

    To fix this problem, use a cast:

    要解决这个问题,请使用cast:

    short z = (short)(x + y);   // OK: explicit conversion
    

    It is possible though to use the following statements, where the destination variable has the same storage size or a larger storage size:

    可以使用以下语句,其中目标变量具有相同的存储大小或更大的存储大小:

    int m = x + y;
    long n = x + y;
    

    A good follow-up question is:

    一个很好的后续问题是:

    "why arithmetic expression on the right-hand side of the assignment operator evaluates to int by default" ?

    为什么赋值运算符右边的算术表达式默认值为int ?

    A first answer can be found in:

    第一个答案可以在:

    Classifying and Formally Verifying Integer Constant Folding

    分类和正式验证整数常数折叠

    The Java language specification defines exactly how integer numbers are represented and how integer arithmetic expressions are to be evaluated. This is an important property of Java as this programming language has been designed to be used in distributed applications on the Internet. A Java program is required to produce the same result independently of the target machine executing it.

    Java语言规范确切地定义了如何表示整数,以及如何计算整数算术表达式。这是Java的一个重要属性,因为这种编程语言已经被设计用于Internet上的分布式应用程序。Java程序需要独立于执行它的目标机器生成相同的结果。

    In contrast, C (and the majority of widely-used imperative and object-oriented programming languages) is more sloppy and leaves many important characteristics open. The intention behind this inaccurate language specification is clear. The same C programs are supposed to run on a 16-bit, 32-bit, or even 64-bit architecture by instantiating the integer arithmetics of the source programs with the arithmetic operations built-in in the target processor. This leads to much more efficient code because it can use the available machine operations directly. As long as the integer computations deal only with numbers being “sufficiently small”, no inconsistencies will arise.

    与之相反,C(以及大多数广泛使用的命令式和面向对象编程语言)则更加松散,并且开放了许多重要的特性。这种不准确的语言规范背后的意图是明确的。相同的C程序应该在16位、32位甚至64位的体系结构上运行,方法是实例化源程序的整数算术,并在目标处理器中内置算术操作。这将导致更高效的代码,因为它可以直接使用可用的机器操作。只要整数计算只处理“足够小”的数字,就不会出现不一致。

    In this sense, the C integer arithmetic is a placeholder which is not defined exactly by the programming language specification but is only completely instantiated by determining the target machine.

    从这个意义上说,C整数算法是一个占位符,它不是由编程语言规范定义的,而是通过确定目标机器来完全实例化的。

    Java precisely defines how integers are represented and how integer arithmetic is to be computed.

    Java精确地定义了整数是如何表示的,以及如何计算整数运算。

          Java Integers
    --------------------------
    Signed         |  Unsigned
    --------------------------
    long  (64-bit) |
    int   (32-bit) |
    short (16-bit) |  char (16-bit)
    byte  (8-bit)  |
    

    Char is the only unsigned integer type. Its values represent Unicode characters, from \u0000 to \uffff, i.e. from 0 to 216−1.

    Char是惟一的无符号整数类型。其值表示Unicode字符,从\ \ uffff u0000,即从0到216−1。

    If an integer operator has an operand of type long, then the other operand is also converted to type long. Otherwise the operation is performed on operands of type int, if necessary shorter operands are converted into int. The conversion rules are exactly specified.

    如果一个整数运算符有一个类型为long的操作数,那么另一个操作数也被转换为long类型。否则,操作将在类型为int的操作数上执行,如果需要,将更短的操作数转换为int。

    [From Electronic Notes in Theoretical Computer Science 82 No. 2 (2003)
    Blesner-Blech-COCV 2003: Sabine GLESNER, Jan Olaf BLECH,
    Fakultät für Informatik,
    Universität Karlsruhe
    Karlsruhe, Germany]

    [摘自《理论计算机科学电子注释》第82期(2003):Blesner-Blech-COCV 2003: Sabine GLESNER, Jan Olaf BLECH, Fakultat fur Informatik, Universitat Karlsruhe Karlsruhe, Germany]

    #2


    17  

    EDIT: Okay, now we know it's Java...

    编辑:好的,现在我们知道是Java…

    Section 4.2.2 of the Java Language Specification states:

    Java语言规范的4.2.2节:

    The Java programming language provides a number of operators that act on integral values:

    Java编程语言提供了许多操作符,它们作用于整数值:

    [...]

    […]

  • The numerical operators, which result in a value of type int or long:
  • 数值运算符,导致类型为int或long:
  • [...]
  • […]
  • The additive operators + and - (§15.18)

  • 加法运算符+和-(§15.18)
  • In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int or long, which is why you need to cast to assign to a short variable.

    换句话说,它就像c#——加法运算符(当应用到整数类型时)只会导致int或long,这就是为什么需要对短变量进行赋值。

    Original answer (C#)

    原始答案(c#)

    In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:

    在c#(您还没有指定语言,所以我猜)中,基本类型上唯一的加法运算符是:

    int operator +(int x, int y);
    uint operator +(uint x, uint y);
    long operator +(long x, long y);
    ulong operator +(ulong x, ulong y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:

    这些在c# 3.0规范7.7.4中。此外,定义了十进制加法:

    decimal operator +(decimal x, decimal y);
    

    (Enumeration addition, string concatenation and delegate combination are also defined there.)

    (这里还定义了枚举添加、字符串连接和委托组合。)

    As you can see, there's no short operator +(short x, short y) operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.

    如您所见,没有短操作符+(短x,短y)操作符——因此两个操作数都隐式地转换为int,并使用int形式。这意味着结果是“int”类型的表达式,因此需要强制转换。

    #3


    16  

    In C# and Java, the arithmatic expression on the right hand side of the assignment evaluates to int by default. That's why you need to cast back to a short, because there is no implicit conversion form int to short, for obvious reasons.

    在c#和Java中,赋值右边的算术表达式默认值为int。这就是为什么您需要返回到一个short,因为由于明显的原因,不存在从int到short的隐式转换。

    #4


    6  

    Given that the "why int by default" question hasn't been answered ...

    既然“为什么int默认”问题还没有得到回答……

    First, "default" is not really the right term (although close enough). As noted by VonC, an expression composed of ints and longs will have a long result. And an operation consisting of ints/logs and doubles will have a double result. The compiler promotes the terms of an expression to whatever type provides a greater range and/or precision in the result (floating point types are presumed to have greater range and precision than integral, although you do lose precision converting large longs to double).

    首先,“违约”并不是真正正确的术语(尽管已经足够接近了)。正如VonC所指出的,一个由int和long组成的表达式将会产生很长的结果。而由ints/log和double组成的操作将产生双重结果。编译器将表达式的术语推广到任何类型,从而在结果中提供更大的范围和/或精度(假定浮点类型具有比整数更大的范围和精度,尽管您确实会丢失将大长转换为双长的精度)。

    One caveat is that this promotion happens only for the terms that need it. So in the following example, the subexpression 5/4 uses only integral values and is performed using integer math, even though the overall expression involves a double. The result isn't what you might expect...

    有一点需要注意的是,这种提升只会发生在需要它的条件下。因此,在下面的示例中,子表达式5/4只使用整数值,并使用整数math执行,即使整个表达式包含一个double。结果并不像你想象的那样……

    (5/4) * 1000.0
    

    OK, so why are byte and short promoted to int? Without any references to back me up, it's due to practicality: there are a limited number of bytecodes.

    为什么字节和短字节被提升为int?没有任何引用来支持我,这是由于实用性:字节码的数量是有限的。

    "Bytecode," as its name implies, uses a single byte to specify an operation. For example iadd, which adds two ints. Currently, 205 opcodes are defined, and integer math takes 18 for each type (ie, 36 total between integer and long), not counting conversion operators.

    “字节码”,顾名思义,使用一个字节来指定操作。例如iadd,它添加了两个ints。目前,已经定义了205个操作码,每种类型的整型数都需要18个(即,整型和长型之间总共36个操作码),不包括转换操作符。

    If short, and byte each got their own set of opcodes, you'd be at 241, limiting the ability of the JVM to expand. As I said, no references to back me up on this, but I suspect that Gosling et al said "how often do people actually use shorts?" On the other hand, promoting byte to int leads to this not-so-wonderful effect (the expected answer is 96, the actual is -16):

    如果每个字节都有自己的一组操作码,那么您的操作码是241,这限制了JVM扩展的能力。就像我说的,没有人支持我的观点,但我怀疑高斯林等人说过“人们到底有多经常穿短裤?”另一方面,将字节提升为int会导致这种不太妙的效果(预期答案是96,实际答案是-16):

    byte x = (byte)0xC0;
    System.out.println(x >> 2);
    

    #5


    5  

    What language are you using?

    你用什么语言?

    Many C based languages have a rule that any mathematical expression is performed in size int or larger. Because of this, once you add two shorts the result is of type int. This causes the need for a cast.

    许多基于C的语言都有一个规则,即任何数学表达式的大小都是整数或整数。正因为如此,一旦你加了两条短裤,结果就是int型的,这就造成了对演员的需求。

    #6


    2  

    Java always uses at least 32 bit values for calculations. This is due to the 32-bit architecture which was common 1995 when java was introduced. The register size in the CPU was 32 bit and the arithmetic logic unit accepted 2 numbers of the length of a cpu register. So the cpus were optimized for such values.

    Java总是使用至少32位值进行计算。这是由于32位架构,这在java引入时是很常见的。CPU中的寄存器大小为32位,算术逻辑单元接受两个CPU寄存器长度的数字。因此,我们对cpu进行了优化。

    This is the reason why all datatypes which support arithmetic opperations and have less than 32-bits are converted to int (32 bit) as soon as you use them for calculations.

    这就是为什么所有支持算术运算并且小于32位的数据类型在您使用它们进行计算时都被转换为int(32位)的原因。

    So to sum up it mainly was due to performance issues and is kept nowadays for compatibility.

    综上所述,它主要是由于性能问题而保留至今的兼容性。

    #7


    1  

    In java, every numeric expression like:

    在java中,每个数值表达式:

    anyPrimitive zas = 1;
    anyPrimitive bar = 3;
    ?? x = zas  + bar 
    

    x will always result to be at least an int, or a long if one of the addition elements was a long.

    x总是至少是一个int数,或者如果其中一个相加元素是长的话,则是一个long。

    But there's are some quirks tough

    但也有一些奇怪的事情

    byte a = 1; // 1 is an int, but it won't compile if you use a variable
    a += 2; // the shortcut works even when 2 is an int
    a++; // the post and pre increment operator work
    

    #8


    1  

    AFAIS, nobody mentions of final usage for that. If you modify your last example and define variables a and b as final variables, then the compiler is assured that their sum, value 5 , can be assigned to a variable of type byte, without any loss of precision. In this case, the compiler is good to assign the sum of a and b to c . Here’s the modified code:

    没有人提到它的最终用法。如果修改上一个示例并将变量a和b定义为最终变量,那么编译器将确保它们的总和(值5)可以分配给类型为byte的变量,而不会丢失任何精度。在这种情况下,编译器最好将a和b的和赋给c。这是修改后的代码:

    final byte a = 2;
    final byte b = 3;
    byte c = a + b;
    

    #9


    1  

    Any data type which is lower than "int" (except Boolean) is implicitly converts to "int".

    任何小于“int”(布尔值除外)的数据类型都隐式地转换为“int”。

    In your case:

    在你的例子:

    short a = 2;
    short b = 3;
    short c = a + b;
    

    The result of (a+b) is implicitly converted to an int. And now you are assigning it to "short".So that you are getting the error.

    (a+b)的结果隐式地转换为int,现在将其赋值为“short”。这样就得到了误差。

    short,byte,char --for all these we will get same error.

    短,字节,字符——对于所有这些,我们会得到相同的错误。

    #10


    0  

    I'd like to add something that hasn't been pointed out. Java doesn't take into account the values you have given the variables (2 and 3) in...

    我想补充一些没有指出的东西。Java没有考虑您在…中给变量(2和3)的值。

    short a = 2; short b = 3; short c = a + b;

    短= 2;短b = 3;短c = a + b;

    So as far as Java knows, you could done this...

    就Java所知,您可以这样做……

    short a = 32767; short b = 32767; short c = a + b;

    短= 32767;短b = 32767;短c = a + b;

    Which would be outside the range of short, it autoboxes the result to an int becuase it's "possible" that the result will be more than a short but not more than an int. Int was chosen as a "default" because basically most people wont be hard coding values above 2,147,483,647 or below -2,147,483,648

    这将是短的范围之外,它autoboxes结果int因为“可能的”,结果将是一个多短但不超过一个int,int基本上被选为“默认”,因为大多数人不会硬编码值高于2147483647或-2147483648以下吗