Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 150
Casting Values vs. Variables
ОглавлениеRevisiting our third numeric promotional rule, the compiler doesn't require casting when working with literal values that fit into the data type. Consider these examples:
byte hat = 1; byte gloves = 7 * 10; short scarf = 5; short boots = 2 + 1;
All of these statements compile without issue. On the other hand, neither of these statements compiles:
short boots = 2 + hat; // DOES NOT COMPILE byte gloves = 7 * 100; // DOES NOT COMPILE
The first statement does not compile because hat
is a variable, not a value, and both operands are automatically promoted to int
. When working with values, the compiler had enough information to determine the writer's intent. When working with variables, though, there is ambiguity about how to proceed, so the compiler reports an error. The second expression does not compile because 700
triggers an overflow for byte
, which has a maximum value of 127
.