简体   繁体   中英

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. 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.

Why can I assign an int to a short , but not long to int ?

The answer is in section 5.2 Assignment Conversion of the JLS :

In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

  • 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.

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 .

There is no similar clause for constant expressions with long values.

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 ).


Please note that your examples 1 and 2 are probably not interpreted as you might think they are. 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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