int x; // объявление переменной
x = 10; // инициализация переменной
x = 21; // присваивание значения переменной
System.out.println(x);
Как с помощью языка программирования хранить информацию в оперативной памяти?
Data types
Variables
Variable (переменная) - это именованная ячейка памяти.
Variable содержит в себе какое-то value (значение).
Value в variable может изменяться в процессе выполнения программы.
int x; // объявление переменной
x = 10; // инициализация переменной
x = 21; // присваивание значения переменной
System.out.println(x);
21
int y = 10; // объявление и инициализация переменной
x = 21; // присваивание значения переменной
System.out.println(y);
21
int z; // объявление переменной
System.out.println(z);
Compile error: java: variable z might not have been initialized
int x, y;
x = 10;
y = 25;
System.out.println(x); // 10
System.out.println(y); // 25
10 25
Bad practice
int a = 8, b = 15;
System.out.println(a);
System.out.println(b);
8 15
Bad practice
int i = 1;
int j = 11;
System.out.println(i);
System.out.println(j);
1 11
Good practice
При объявлении переменной:
сначала указывается data type (тип данных) переменной
затем identifier (идентификатор) задаваемой переменной
например: int age
.
Identifiers (идентификаторы) – это имена, которые даются различным элементам языка для упрощения доступа к ним.
Identifiers регистрозависимые, т.е. AGE
и age
совершенно разные identifiers
Identifiers должны быть УНИКАЛЬНЫ в рамках текущего блока
В именах переменных разрешено использовать символы:
A
-Z
a
-z
0
-9
$
, _
В именах переменных запрещено применение:
цифры в качестве первого символа
ТОЛЬКО одного символа _
(error: as of release 9, '_' is a keyword, and may not be used as an identifier)
Possible | Impossible |
---|---|
|
|
|
|
|
|
Как правило:
Переменные именуются с использованием camelCase
.
Название должно объяснять что за значение находится в переменной.
int cargo = 11;
int carryingCapacity = 2;
int depositAmount = 1500;
int depositYears = 5;
int depositAnnualPercentage = 3;
Тип | Размер | Мин | Макс |
---|---|---|---|
| 1 byte |
|
|
| 2 bytes |
|
|
| 4 bytes |
|
|
| 8 bytes |
|
|
Тип | Размер | Мин | Макс |
---|---|---|---|
| 1 byte |
|
|
| 2 bytes |
|
|
| 4 bytes |
|
|
| 8 bytes |
|
|
Тип | Размер | Описание |
---|---|---|
| 4 bytes | Single-precision 32-bit IEEE 754 floating point |
| 8 bytes | Double-precision 64-bit IEEE 754 floating point |
The IEEE Standard for Floating-Point Arithmetic (IEEE 754) is a technical standard for floating-point arithmetic established in 1985 by the Institute of Electrical and Electronics Engineers (IEEE)
Тип | Размер | Описание |
---|---|---|
| 4 bytes | Single precision: |
| 8 bytes | Double precision: |
Тип | Размер | Мин | Макс |
---|---|---|---|
| 1 bit |
|
|
Тип | Размер | Мин | Макс |
---|---|---|---|
| 2 bytes |
|
|
Unicode, formally the Unicode Standard, is an information technology standard for the consistent encoding, representation, and handling of text expressed in most of the world’s writing systems
Тип | Размер | Мин | Макс |
---|---|---|---|
| 2 bytes |
|
|
Literals (литералы) — это явно заданные значения в исходном коде программы.
class Example {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
All integer values are integer literals
For big integer values use suffix l
OR L
int i = 1234567;
// long a = 12345678901; // error: integer number too large
long b = 12345678901L;
long c = 12345678901l; // Not recommend. Use `L`
1234567 12345678901 12345678901
Decimal:
possible chars are 0
, 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, 9
Binary:
representation starts with 0B
or 0b
possible chars are 0
, 1
Octal:
representation starts with 0
possible chars are 0
, 1
, 2
, 3
, 4
, 5
, 6
, 7
Hexadecimal:
representation starts with 0X
or 0x
possible chars are 0
, 1
, 2
, 3
, 4
, 5
, 6
, 7
, 8
, 9
, a
, b
, c
, d
, e
, f
, A
, B
, C
, D
, E
, F
int decimalNumber = 42;
int binaryNumber = 0b101010;
int octalNumber = 052;
int hexadecimalNumber = 0x2A;
42 42 42 42
All double
values are floating point literals
For float
values use suffix f
OR F
For double
values, suffix d
OR D
can be used (this is optional)
double d1 = 2.123;
double d2 = 2.123d;
double d3 = 2.123D;
double d4 = 4.05E-13; // Тип double в экспоненциальной записи
2.123 2.123 2.123 4.05E-13
double d5 = .5; // Тип double эквивалентный 0.5
double d6 = 3.; // Тип double эквивалентный 3.0
double d7 = 0.0 / 0.0; // Not-a-Number
double d8 = 1.0 / 0.0; // бесконечность
double d9 = -1.0 / 0.0; // отрицательная бесконечность
0.5 3.0 NaN Infinity -Infinity
// float d = 2.718; // error: incompatible types: possible lossy conversion from double to float
float f2 = 2.718f;
float f1 = 2.718F;
float f3 = 0.0f / 0.0f; // Not-a-Number
float f4 = 1.0f / 0.0f; // бесконечность
float f5 = -1.0f / 0.0f; // отрицательная бесконечность
2.718 2.718 NaN Infinity -Infinity
_
and Numeric Literals_
an appear anywhere between digits in a numerical literal
_
can improve the readability of your code
_
and Numeric LiteralsCannot place _
in the following places:
At the beginning or end of a number
Adjacent to a decimal point in a floating point literal
Prior to an F
or L
suffix
int a = 123456789;
int b = 123_456_789;
int c = 123___456______789;
double d = 0.123_456_789;
123456789 123456789 123456789 0.123456789
start with '
contains ONE char without symbols: \
, '
end with '
char c1 = 'A';
A
start with "
contains chars without symbols: \
, "
end with "
String text = "text literal";
text literal
\
Escape symbol \
combine with:
A single character: b
, t
, n
, f
, r
, "
, '
, \
An octal number between 000
and 377
A u
followed by four hexadecimal digits specifying a Unicode character
char c1 = 'A'; // A (latin) Glyph
char c2 = '\u0041'; // A (latin) Unicode
char c3 = '\101'; // A (latin) Octal
char c4 = 65; // A (latin) Decimal
String s1 = "\u0041"; // A (latin) Unicode
String s2 = "\101"; // A (latin) Octal
A A A A A A
\
Escape Sequence | Unicode | Description |
---|---|---|
|
| Backspace |
|
| Horizontal tab |
|
| Linefeed |
|
| Form feed |
|
| Carriage return |
|
| Double quotation mark - |
|
| Single quotation mark - |
|
| Backslash - |
Octal Literal | Unicode | Description |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
| Double quotation mark |
Don’t use the Unicode format to express an end-of-line character.
Use the \n
or \r
characters instead.
System.out.print("text\ntext");
// System.out.print("\u000a"); // a compiler error;
// System.out.print('\u000a'); // a compiler error;
text text
start with {
contains values separated with ,
(comma)
end with }
int[] ages = {15, 45, 34, 67, 89};
Point[] points = {new Point(1.0, 2.1), new Point(-3.4, 5.1)}
true
false
But they are keywords
boolean enabled = false;
boolean isRun = true;
false true
null
null
represent a void reference
null
is a pointer to nothing
But null
is keyword
String text = null;
null
Кроме переменных, в Java для хранения данных можно использовать константы.
Константы позволяют задать такие переменные, которые не должны больше изменяться.
В отличие от переменных константам можно присвоить значение ТОЛЬКО один раз.
Объявляется, как и переменные, но только со служебным словом final
.
Как правило:
Константы именуются с использованием UPPER_SNAKE_CASE
.
Название константы должно объяснять, что за значение находится в ней.
final int LIMIT = 5;
final String NUMBER_SYSTEM = "BINARY";
Widening Casting (automatically)
Narrowing Casting (manually)
short a = 'Z';
System.out.println(a); // 90
double b = 1_234_567_890_123_456L;
System.out.println(b); // 1.234567890123456E15
float c1 = 1_234_567_890_123_456L;
System.out.println(c1); // 1.23456795E15
float c2 = 123_456_789;
System.out.println(c2); // 1.23456792E8
double c3 = 1_234_567_890_123_456_789L;
System.out.println(c3); // 1.23456789012345677E18
byte d = 128; // error: incompatible types: possible lossy conversion from int to byte
char e = 2L; // error: incompatible types: possible lossy conversion from long to char
short f = '\uffff'; // error: incompatible types: possible lossy conversion from char to short
byte i1 = (byte) 128;
byte i2 = (byte) 129;
System.out.println(i1); // -128
System.out.println(i2); // -127
Пробелы
Комментарии
Лексемы
Whitespace (Пробел) - ASCII 32
CR
- ASCII 10
LF
(NL
) - ASCII 13
TAB
- ASCII 9
Однострочный
// java 4 U
Многострочный
i++/* increment comment*/;
Документирования
/** * @author Dmitry Rakovets */
ключевые слова (key words)
идентификаторы (identifiers)
литералы (literals)
разделители (separators)
операторы (operators)
abstract continue for new switch
assert default if package synchronized
boolean do goto private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const float native super while
_ (underscore)
( ) [ ] { } ; . ,
var
var
(@since 10
)var x = 10;
System.out.println(x); // 10
var
(@since 10
)var y; // error: cannot infer type for local variable y
y = 10;
Java - строго типизированный язык программирования.
Типы переменных должны быть известны до compile time
(@since 10) или могут ОДНОЗНАЧНО установлены во время compile time
It is because java uses Unicode system not ASCII code system.
The \u0000
is the lowest range of Unicode system.