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, 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?

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 is null. According to primitives, literals are also divided into sections:
  1. Numeric:
    • Integers;
    • floating point;
  2. string;
  3. Symbolic;
  4. 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
JDK 7 introduced the ability to write binary values. This is done using the prefix 0b or 0B . Next comes the notation using 0 and 1. Numbers in octal are written with 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: the numbers are indicated in the form we are used to. The only restriction is that the number cannot start with 0, as the compiler will take it as octal. Numbers in hexadecimal are written using the prefixes 0x and 0X. Valid digits are from 0 to 15, where the numbers 10-15 are denoted by the symbols AF, 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 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, longit 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 for at the end F. In this case, doubleit 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:
  1. Those that can be entered from the keyboard are ordinary characters;
  2. Symbols that cannot be simply entered from the keyboard (characters of various languages, shapes, and so on).
Regular characters can be specified explicitly: ' ,' 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: falseand 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.

Literals in CodeGym course

In the CodeGym 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. CodeGym is an online Java programming course with an emphasis on practice: 1200+ tasks with instant verification, mini-projects, games.

Conclusion

Literals in Java are a handy thing in any program, but they should be used where appropriate. You should not hardcode in the sources the parameters for connecting to the database or any values ​​that may change during the life cycle of the program.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION