JavaRush /Java Blog /Random EN /Literals in Java

Literals in Java

Published in the Random EN group
At the stage of creating an application, the developer, as a rule, knows only its structure and does not assume what data it will process. However, in some situations, you need to explicitly specify some data in the program code (for example, the number of iterations or the message to be output). In this case, literals come to the rescue. Content:

What are literals?

Literals are explicitly specified values ​​in the program code - constants of a certain type that are in the code at the time of launch.
class Test {
   public static void main(String[] args) {
       System.out.println("Hello world!");
   }
}
In this class “Hello world!” - literal. Literals come in different types, determined by their purpose and how they are written.

Types of literals and their uses

All literals are primitive values ​​(strings, numbers, characters, booleans). You cannot create a literal object. The only literal associated with an object is null. According to primitives, literals are also divided into sections:
  1. Numeric:
    • Integers;
    • Floating point;
  2. String;
  3. Character;
  4. Brain teaser.

Numeric literals

Integer literals

This type of literal is the simplest. Numbers are written in their standard form without indicating characters or anything else. Any integer is an integer literal by default. That is, you can explicitly set the value of a variable or the number of iterations in a loop. Java supports 4 number systems:
  • Binary
  • Octal
  • Decimal
  • Hexadecimal
JDK 7 introduced the ability to write binary values. This is done using the prefix 0b or 0B . Next comes writing using 0 and 1. Numbers in octal are written using a leading 0. Valid digits are 0 through 7. Writing 09 or 08 will cause a compilation error. There are no problems with the decimal number system: numbers are indicated in the form we are familiar with. The only limitation is that the number cannot start with 0, since the compiler will take it as octal. Numbers in hexadecimal are written using the prefixes 0x and 0X. Valid numbers are from 0 to 15, where numbers 10-15 are indicated by AF symbols respectively.
public static void main(String[] args) {
       int a = 0b1101010110;
       int b = 012314;
       int c = 456;
       int d = 0x141D12;
       System.out.println("Число a в двоичной системе: " + a);
       System.out.println("Число b в восьмеричной системе: " + b);
       System.out.println("Число c в десятичной системе: " + c);
       System.out.println("Число d в шестнадцатеричной системе: " + d);
}
Output: Number a in binary system: 854 Number b in octal system: 5324 Number c in decimal system: 456 Number d in hexadecimal system: 1318162 Despite the fact that numbers are specified in different number systems, in the program they are processed as decimal numbers. Exceeding the values ​​will result in a compilation error:
int b = 012914; // Ошибка
int d = 0x141Z12; // Ошибка
When run at the compilation stage, we get the following result:

Error:(13, 25) java: integer number too large: 012914
Error:(14,30) java: ';' expected
What about typing? Any integer literal has a default type of int. If its value is outside the bounds of the assigned variable, a compilation error occurs. When using a type, longyou must put a symbol at the end Lindicating this type:
long x = 0x1101010110; // Ошибка
long b = 1342352352351351353L; // Все в порядке
Trying to compile results in the following error:

Error(11, 26) java: integer number too large: 1101010110

Floating point literals

Floating point numbers, or fractional numbers, can be written in two ways. The first is as a classic decimal fraction: 3.14159 or 2.718281282459045. The second is in scientific form, that is, an ordinary decimal fraction plus a suffix in the form of the symbol e or E and the power of 10 by which the specified fraction must be multiplied. For example, 4.05E-13, this means 4.05 * 10 -13 .
double a = 2.718281828459045;
double d = 4.05E-13;
System.out.println("Тип double в классическом виде: " + a);
System.out.println("Тип double в научном виде: " + d);
Output: Classic double type: 2.718281828459045 Scientific double type: 4.05E-13 Unlike integers and number systems, scientific notation is stored in a variable and processed in the same way as classical notation. What about typing? Any floating point number creates a type double. If you must use the type float, you must add an for at the end F. In this case doubleit will be reduced to type float. This does not happen automatically:
float a = 2.718281828459045; // Ошибка
float d = 4.05E-13F; // Все в порядке
When starting at the compilation stage we see the following error:

Error:(11, 27) java: incompatible types: possible lossy conversion from double to float

String literals

String literals are a set of characters enclosed in double quotes. This type is used as often as numeric literals. The line may also contain service characters that need to be escaped (so-called escape sequences). Example:
String simpleString = "Это обычная строка. Такая же стандартная и непримечательная, How и все мы.";
String uniqueString = "А это необычная \"строка\". Хотя бы потому, что часть \"слов\" в ней в \"кавычках\".";
System.out.println(simpleString);
System.out.println(uniqueString);
Output: This is a normal string. Just as standard and unremarkable as the rest of us. And this is an unusual “line”. If only because some of the “words” in it are in “quotes”.

Character literals

Character literals in Java are represented by the Unicode character set, that is, each character is a 16-bit value. To indicate a symbol in the code, it is separated by single quotes. Based on experience, there are two types of symbols:
  1. Those that can be entered from the keyboard are ordinary characters;
  2. Symbols that cannot be simply entered from the keyboard (symbols of various languages, shapes, and so on).
Regular characters can be specified explicitly: ' ,' or ' @'. If a character is a service character (for example, a line break or tab), such a character must be escaped with a backslash. Characters that cannot simply be entered from the console can be specified in their 16-bit form. To do this, you must specify the character code with a prefix \u, for example ' \u00F7'. You can also specify characters in octal style (three-digit number) by simply adding a backslash at the beginning, for example ' \122'. In my opinion, it is much easier to use \u. Usage example:
System.out.println("Амперсанд - " + '&');
System.out.println("Символ деления - " + '\u00F7');
Output: Ampersand - & Division symbol - ÷

Boolean literals

The simplest literal is a logical one. There are only 2 values: falseand true, which are specified explicitly without various symbols. Such literals can be assigned to variables of type boolean or specified in a place where type boolean is expected (for example, in an if block, although this practice is considered bad manners, to put it mildly).
boolean flag = false;

if(true) {
    // Действия будут выполняться всегда.
}

Jedi technique with literals

Thanks to symbols in Java, you can do many interesting things, including managing emojis. For example, let's display a smiling face:
int smile = 0x1F600; // Здесь шестнадцатеричный code эмоджи
StringBuilder sb = new StringBuilder();
sb.append(Character.toChars(smile)); // Собираем в StringBuilder
System.out.println("Улыбающееся лицо: " + sb.toString()); // Выводим
Conclusion: Smiling face: 😀 Although the emoji display can be creepy (depending on the implementation), this solution does the job well. However, it is difficult to search for the desired emoji in the standard encoding table; the Emoticon section on the official website is sparse. It is much easier to use additional libraries.

Literals in the JavaRush course

In the JavaRush course, literals are studied at level 10 in lecture 8 of the Java Syntax course , where examples explain what literals are and why they are needed. JavaRush is an online course on Java programming with an emphasis on practice: 1200+ tasks with instant verification, mini-projects, games.

Conclusion

Literals in Java are a convenient thing in any program, but they must be used in those places where it is appropriate. You should not hardcode database connection parameters or any values ​​that may change during the program's life cycle in the source code.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION