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
- Types of literals and their uses
- Numeric literals
- String literals
- Character literals
- Boolean literals
- Jedi technique with literals
- Literals in the JavaRush course
- Conclusion
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 isnull
. According to primitives, literals are also divided into sections:
- Numeric:
- Integers;
- Floating point;
- String;
- Character;
- 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
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, long
you must put a symbol at the end L
indicating 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 f
or at the end F
. In this case double
it 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:- Those that can be entered from the keyboard are ordinary characters;
- Symbols that cannot be simply entered from the keyboard (symbols of various languages, shapes, and so on).
,
' 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:false
and 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.
GO TO FULL VERSION