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, it is necessary to explicitly specify some data in the program code (for example, the number of iterations or a message to display). This is where literals come to the rescue. Content:
- What are literals
- Literal types and their uses
- Numeric literals
- String literals
- Character literals
- Boolean literals
- Jedi Technique with Literals
- Literals in CodeGym course
- Conclusion
What are literals?
Literals are explicitly set 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, which are determined by their purpose and the way they are written.
Literal types and their uses
All literals are primitive values (strings, numbers, characters, booleans). You cannot create an object literal. The only literal associated with an object isnull
. According to primitives, literals are also divided into sections:
- Numeric:
- Integers;
- floating point;
- string;
- Symbolic;
- Brain teaser.
Numeric literals
Integer literals
This type of literal is the simplest. Numbers are written in their standard form without indicating symbols and other things. 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 the 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 Although the numbers are specified in different number systems, they are treated as decimal numbers in the program. Going beyond the values will result in a compilation error:
int b = 012914; // Ошибка
int d = 0x141Z12; // Ошибка
When run at compile time, 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 is of type by default int
. If its value is outside the bounds of the variable being assigned, a compilation error occurs. When using a type, long
it is necessary to put a symbol at the end L
, denoting this type:
long x = 0x1101010110; // Ошибка
long b = 1342352352351351353L; // Все в порядке
Attempting 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: 3.14159 or 2.718281282459045. The second is in scientific form, that is, the usual decimal fraction plus a suffix in the form of the symbol e or E and the power of 10 by which the indicated fraction must be multiplied. For example, 4.05E-13 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: Type double in classical form: 2.718281828459045 Type double in scientific form: 4.05E-13 Unlike integers and number systems, scientific notation is stored in a variable and is processed in the same way as the classical form. What about typing? Any floating point number creates a double
. If you want to use the type float
, add an f
or at the end F
. In this case, double
it will be cast to type float
. This does not happen automatically:
float a = 2.718281828459045; // Ошибка
float d = 4.05E-13F; // Все в порядке
When running 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 string may also contain service characters that need to be escaped (the so-called escape sequences). Example:String simpleString = "Это обычная строка. Такая же стандартная и непримечательная, How и все мы.";
String uniqueString = "А это необычная \"строка\". Хотя бы потому, что часть \"слов\" в ней в \"кавычках\".";
System.out.println(simpleString);
System.out.println(uniqueString);
Output: This is a regular 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 "quotation marks".
Character literals
Character literals in Java are represented by the Unicode character set, meaning that each character is a 16-bit value. To designate a character in the code, it is separated by single quotes. According to the experience of use, 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 (characters of various languages, shapes, and so on).
,
' or ' @
'. If the character is a service character (for example, a line break or a tab), such a character must be escaped with a backslash. Characters that cannot be simply 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
, such as ' \u00F7
'. Also, characters can be specified in octal style (three-digit number) by adding a simple backslash at the beginning, such as ' \122
'. In my opinion it's much easier to use \u
. Usage example:
System.out.println("Амперсанд - " + '&');
System.out.println("Символ деления - " + '\u00F7');
Output: Ampersand - & Division symbol - ÷
Boolean literals
The simplest literal is boolean. There are only 2 values:false
and true
, which are specified explicitly without different symbols. Such literals can be assigned to variables of type boolean or specified in a place where a boolean type is expected (for example, in an if block, although this practice is considered, to put it mildly, bad manners).
boolean flag = false;
if(true) {
// Действия будут выполняться всегда.
}
Jedi Technique with Literals
Thanks to the symbols in Java, you can do a lot of interesting things, including managing emoji. For example, let's draw 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: 😀 Even though the emoji display can be creepy (depending on the implementation), this solution does the job well. However, it is difficult to search for the necessary emojis in the standard encoding table; on the official website, the Emoticon section is poor. It is much easier to use additional libraries.
GO TO FULL VERSION