Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 147

Reviewing Primitive Assignments

Оглавление

See if you can figure out why each of the following lines does not compile:

int fish = 1.0; // DOES NOT COMPILE short bird = 1921222; // DOES NOT COMPILE int mammal = 9f; // DOES NOT COMPILE long reptile = 192_301_398_193_810_323; // DOES NOT COMPILE

The first statement does not compile because you are trying to assign a double 1.0 to an integer value. Even though the value is a mathematic integer, by adding .0, you're instructing the compiler to treat it as a double. The second statement does not compile because the literal value 1921222 is outside the range of short, and the compiler detects this. The third statement does not compile because the f added to the end of the number instructs the compiler to treat the number as a floating-point value, but the assignment is to an int. Finally, the last statement does not compile because Java interprets the literal as an int and notices that the value is larger than int allows. The literal would need a postfix L or l to be considered a long.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх