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

Writing Literals

Оглавление

There are a few more things you should know about numeric primitives. When a number is present in the code, it is called a literal. By default, Java assumes you are defining an int value with a numeric literal. In the following example, the number listed is bigger than what fits in an int. Remember, you aren't expected to memorize the maximum value for an int. The exam will include it in the question if it comes up.

long max = 3123456789; // DOES NOT COMPILE

Java complains the number is out of range. And it is—for an int. However, we don't have an int. The solution is to add the character L to the number:

long max = 3123456789L; // Now Java knows it is a long

Alternatively, you could add a lowercase l to the number. But please use the uppercase L. The lowercase l looks like the number 1.

Another way to specify numbers is to change the “base.” When you learned how to count, you studied the digits 0–9. This numbering system is called base 10 since there are 10 possible values for each digit. It is also known as the decimal number system. Java allows you to specify digits in several other formats:

 Octal (digits 0–7), which uses the number 0 as a prefix—for example, 017.

 Hexadecimal (digits 0–9 and letters A–F/a–f), which uses 0x or 0X as a prefix—for example, 0xFF, 0xff, 0XFf. Hexadecimal is case insensitive, so all of these examples mean the same value.

 Binary (digits 0–1), which uses the number 0 followed by b or B as a prefix—for example, 0b10, 0B10.

You won't need to convert between number systems on the exam. You'll have to recognize valid literal values that can be assigned to numbers.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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