SlideShare a Scribd company logo
Базовый синтаксис
Алексей Владыкин
Примитивные типы
boolean
char
byte, short, int, long
float, double
Примитивные типы
int a = 100;
int b = a;
Ссылочные типы
String s = "Hello world!";
String t = s;
String u = null;
Тип boolean
boolean brushedTeethToday = true;
boolean haveDog = false;
boolean iKnowMath = 1 < 100;
boolean fromInt = 10;
Тип boolean
boolean haveSpareTime = !isBusy;
boolean canGoToPark =
haveSpareTime && weatherIsGood;
boolean hadGoodTime =
learnedJavaOnStepic || wentToPark;
boolean tastesGood =
addedKetchup ^ addedHoney;
Тип boolean
value &= expression;
// value = value & expression;
value |= expression;
// value = value | expression;
value ^= expression;
// value = value ^ expression;
Целочисленные типы
Тип Бит Диапазон
byte 8 −128 .. + 127
short 16 −215
.. + 215
− 1
int 32 −231
.. + 231
− 1
long 64 −263
.. + 263
− 1
Целочисленные типы
int decimal = 99;
int octal = 0755;
int hex = 0xFF;
int binary = 0b101;
int tenMillion = 10 _000_000;
long tenBillion = 10 _000_000_000L;
Арифметические операции
int sum = a + b;
int diff = a - b;
int mult = a * b;
int div = a / b;
int rem = a % b;
int inc = a++ + ++b;
int dec = --a - b--;
Переполнение
byte b = 127;
b++;
Побитовые операции
int neg = ~a;
int and = a & b;
int or = a | b;
int xor = a ^ b;
int arithmeticShiftRight = a >> b;
int logicalShiftRight = a >>> b;
int shiftLeft = a << b;
Тип char
16 бит, беззнаковый, 0 .. 216 − 1
Представляет номер символа в кодировке Unicode
Тип char
char literal = ’a’;
char tab = ’t’;
char lineFeed = ’n’;
char carriageReturn = ’r’;
char singleQuote = ’’’;
char backslash = ’’;
char hex = ’u03A9 ’;
Вещественные типы
Тип Бит Знак Мантисса Экспонента
float 32 1 23 8
double 64 1 52 11
Литералы
double simple = -1.234;
double exponential = -123.4e-2;
double hex = 0x1.Fp10;
float floatWithSuffix = 36.6f;
double doubleWithSuffix = 4d;
Арифметические операции
double sum = a + b;
double diff = a - b;
double mult = a * b;
double div = a / b;
double rem = a % b;
double inc = a++ + ++b;
double dec = --a - b--;
Особые случаи
double positiveInfinify = 1.0 / 0.0;
double negativeInfinify = -1.0 / 0.0;
double nan = 0.0 / 0.0;
boolean notEqualsItself = nan != nan;
Особые случаи
x + eps == x
0.1 + 0.1 + ... + 0.1 != 1
Класс Math
double s = Math.sin(Math.PI);
double q = Math.sqrt (16);
double r = Math.ceil (1.01);
int a = Math.abs ( -13);
int m = Math.max(10, 20);
Длинная арифметика
BigInteger two = BigInteger.valueOf (2);
BigInteger powerOfTwo = two.pow (100);
BigDecimal one = BigDecimal.valueOf (1);
BigDecimal divisionResult =
one.divide(new BigDecimal(powerOfTwo ));
Преобразование типов
byte byteValue = 123;
short shortValue = byteValue;
int intValue = shortValue;
long longValue = intValue;
char charValue = ’@’;
int intFromChar = charValue;
long longFromChar = charValue;
double doubleFromFloat = 1f;
float floatFromLong = longValue;
double doubleFromInt = intValue;
Преобразование типов
int intValue = 1024;
byte byteValue = (byte) intValue;
double pi = 3.14;
int intFromDouble = (int) pi;
float largeFloat = 1e20f;
int intFromLargeFloat = (int) largeFloat;
double largeDouble = 1e100;
float floatFromLargeDouble = (float) largeDouble;
Автоматическое расширение
double doubleValue = 1d + 1f;
float floatValue = 1f * 1;
long longValue = 1L - ’0’;
byte a = 1;
byte b = 2;
byte c = (byte) (a + b);
Неявное приведение
byte a = 1;
a += 3;
// a = (byte) (a + 3);
byte b = -1;
b >>>= 7;
// b = (byte) (b >>> 7);
Классы-обертки
boolean Boolean
byte Byte
short Short
int Integer
long Long
char Character
float Float
double Double
Классы-обертки
int primitive = 0;
Integer reference = Integer.valueOf(primitive );
int backToPrimitive = reference.intValue ();
Классы-обертки
Integer a = 1;
int b = a;
Integer c = 10;
Integer d = 10;
Integer e = c + d;
Конвертация в строку и обратно
long fromString = Long.parseLong("12345");
String fromLong = Long.toString (12345);
String concatenation = "area" + 51;
Полезные методы
short maxShortValue = Short.MAX_VALUE;
int bitCount = Integer.bitCount (123);
boolean isLetter = Character.isLetter(’a’);
float floatInfinity = Float.POSITIVE_INFINITY;
double doubleNaN = Double.NaN;
boolean isNaN = Double.isNaN(doubleNaN );
Объявление vs выделение памяти
BigInteger number;
number = new BigInteger("12345");
Массивы
int[] numbers;
String [] args;
boolean bits [];
Массивы
int[] numbers = new int [100];
String [] args = new String [1];
boolean [] bits = new boolean [0];
Массивы
int[] numbers = new int[] {1, 2, 3, 4, 5};
boolean [] bits = new boolean [] {true , false };
// this works only in variable declaration
char [] digits = {
’0’, ’1’, ’2’, ’3’, ’4’,
’5’, ’6’, ’7’, ’8’, ’9’};
Массивы
int[] numbers = {1, 2, 3, 4, 5};
int arrayLength = numbers.length;
int firstNumber = numbers [0];
int lastNumber = numbers[arrayLength - 1];
int indexOutOfBounds = numbers [5];
Массивы
int [][] matrix1 = new int [2][2];
int [][] matrix2 = {{1, 2}, {3, 4}};
int[] firstRow = matrix2 [0];
int someElement = matrix2 [1][1];
Массивы
int [][] triangle = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9},
{10, 11, 12},
{13, 14},
{15}};
int secondRowLength = triangle [1]. length;
Varargs
static int maxArray(int[] numbers) { ... }
static int maxVarargs(int ... numbers) { ... }
Сравнение массивов
int[] a = {1, 2, 3};
int[] b = {4, 5, 6};
boolean equals1 = a == b;
boolean equals2 = a.equals(b);
boolean equals3 = Arrays.equals(a, b);
boolean equals4 = Arrays.deepEquals(a, b);
Как распечатать массив
int[] a = {1, 2, 3};
System.out.println(a);
System.out.println(Arrays.toString(a));
System.out.println(Arrays.deepToString(a));
Строки
String hello = "Hello";
String specialChars = "rnt"";
String empty = "";
char [] charArray = {’a’, ’b’, ’c’};
String string = new String(charArray );
char [] charsFromString = string.toCharArray ();
String zeros = "u0000u0000";
Строки
String s = "stringIsImmutable";
int length = s.length ();
char firstChar = s.charAt (0);
boolean endsWithTable = s.endsWith("table");
boolean containsIs = s.contains("Is");
Строки
String s = "stringIsImmutable";
String substring = s.substring (0, 6);
String afterReplace = s.replace("Imm", "M");
String allCapitals = s.toUpperCase ();
Строки
String hello = "Hello ";
String world = "world!";
String helloWorld = hello + world;
StringBuilder sb = new StringBuilder ();
sb.append(hello );
sb.append(world );
String helloWorld = sb.toString ();
Строки
boolean referenceEquals = s1 == s2;
boolean contentEquals = s1.equals(s2);
boolean contentEqualsIgnoreCase =
s1.equalsIgnoreCase(s2);
Оператор if
if (weatherIsGood) {
walkInThePark ();
} else {
learnJavaOnStepic ();
}
Оператор ?:
if (weatherIsGood) {
System.out.println("Weather is good");
} else {
System.out.println("Weather is bad");
}
// same effect , but much shorter
System.out.println("Weather is "
+ (weatherIsGood ? "good" : "bad"));
Оператор switch
switch (digit) {
case 0:
text = "zero";
break;
case 1:
text = "one";
break;
// ...
default:
text = "???";
}
Цикл while
while (haveTime () && haveMoney ()) {
goShopping ();
}
Цикл do while
do {
goShopping ();
} while (haveTime () && haveMoney ());
Цикл for
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
Цикл foreach
for (String arg : args) {
System.out.println(arg);
}
Оператор break
boolean found = false;
for (String element : haystack) {
if (needle.equals(element )) {
found = true;
break;
}
}
Оператор continue
int count = 0;
for (String element : haystack) {
if (! needle.equals(element )) {
continue;
}
count ++;
}
Метки
boolean found = false;
outer:
for (int[] row : matrix) {
for (int x : row) {
if (x > 100) {
found = true;
break outer;
}
}
}
Методы
private static String getGreeting(String name) {
if (name == null) {
return "Hello anonymous!";
} else {
return "Hello " + name + "!";
}
}

More Related Content

PDF
C++ Programming - 1st Study
PDF
Data Structure - 2nd Study
PDF
C++ Programming - 4th Study
DOCX
Programa en C++ ( escriba 3 números y diga cual es el mayor))
DOCX
Mouse programming in c
PPT
Cquestions
C++ Programming - 1st Study
Data Structure - 2nd Study
C++ Programming - 4th Study
Programa en C++ ( escriba 3 números y diga cual es el mayor))
Mouse programming in c
Cquestions

What's hot (20)

PPTX
Function basics
PDF
Understanding storage class using nm
PPTX
Double linked list
PPTX
โปรแกรมย่อยและฟังชันก์มาตรฐาน
PDF
Implementing string
DOC
Final ds record
DOCX
C program to implement linked list using array abstract data type
PPTX
การพัฒนาโปรแกรม เลขที่26
PPTX
Programming ppt files (final)
PDF
C Prog - Array
PPTX
3. chapter ii
PDF
C++ Programming - 14th Study
PDF
C++ Programming - 3rd Study
PPTX
PPTX
4. chapter iii
KEY
「Frama-Cによるソースコード検証」 (mzp)
Function basics
Understanding storage class using nm
Double linked list
โปรแกรมย่อยและฟังชันก์มาตรฐาน
Implementing string
Final ds record
C program to implement linked list using array abstract data type
การพัฒนาโปรแกรม เลขที่26
Programming ppt files (final)
C Prog - Array
3. chapter ii
C++ Programming - 14th Study
C++ Programming - 3rd Study
4. chapter iii
「Frama-Cによるソースコード検証」 (mzp)
Ad

Viewers also liked (20)

PDF
Глава 3: примитивные типы и операции с ними в Java
PDF
4.6 Особенности наследования в C++
PDF
3.2 Методы
PDF
5.4 Ключевые слова static и inline
PDF
3.5 Модификаторы доступа
PDF
Программирование: теоремы и задачи
PDF
3. Объекты, классы и пакеты в Java
PDF
3.3 Конструкторы и деструкторы
PDF
5.1 Перегрузка операторов
PDF
4.1 Наследование
PDF
6.1 Шаблоны классов
PDF
6. Generics. Collections. Streams
PDF
1. Введение в Java
PDF
3.8 Класс массива
PDF
3.1 Структуры
PDF
2.8 Строки и ввод-вывод
PDF
6.3 Специализация шаблонов
PDF
6.2 Шаблоны функций
PDF
4.2 Перегрузка
PDF
3.4 Объекты и классы
Глава 3: примитивные типы и операции с ними в Java
4.6 Особенности наследования в C++
3.2 Методы
5.4 Ключевые слова static и inline
3.5 Модификаторы доступа
Программирование: теоремы и задачи
3. Объекты, классы и пакеты в Java
3.3 Конструкторы и деструкторы
5.1 Перегрузка операторов
4.1 Наследование
6.1 Шаблоны классов
6. Generics. Collections. Streams
1. Введение в Java
3.8 Класс массива
3.1 Структуры
2.8 Строки и ввод-вывод
6.3 Специализация шаблонов
6.2 Шаблоны функций
4.2 Перегрузка
3.4 Объекты и классы
Ad

Similar to 2. Базовый синтаксис Java (20)

PDF
Android Development Course in HSE lecture #2
PPTX
Lecture 3.pptx
PPTX
Groovy puzzlers jug-moscow-part 2
PDF
Java 스터디 강의자료 - 1차시
PPT
Wrapper_Classes.ppt.....................
PPTX
บทที่ 3 พื้นฐานภาษา Java
PPTX
Lecture 3 and 4.pptx
PDF
Introduction to Groovy
PPS
Wrapper class
PDF
Airoli_Grade 10_CompApp_PP000000000000000000000000000000000000000000T_Charact...
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
PDF
Lecture20 vector
PPT
Wrapper class (130240116056)
PPSX
Dr. Rajeshree Khande : Programming concept of basic java
PPSX
Dr. Rajeshree Khande : Java Basics
PPTX
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
PDF
03-Primitive-Datatypes.pdf
PDF
vision_academy_classes_Bcs_bca_bba_java part_2 (1).pdf
PDF
Vision academy classes_bcs_bca_bba_java part_2
PPTX
Chapter i(introduction to java)
Android Development Course in HSE lecture #2
Lecture 3.pptx
Groovy puzzlers jug-moscow-part 2
Java 스터디 강의자료 - 1차시
Wrapper_Classes.ppt.....................
บทที่ 3 พื้นฐานภาษา Java
Lecture 3 and 4.pptx
Introduction to Groovy
Wrapper class
Airoli_Grade 10_CompApp_PP000000000000000000000000000000000000000000T_Charact...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Lecture20 vector
Wrapper class (130240116056)
Dr. Rajeshree Khande : Programming concept of basic java
Dr. Rajeshree Khande : Java Basics
Programming Java - Lection 04 - Generics and Lambdas - Lavrentyev Fedor
03-Primitive-Datatypes.pdf
vision_academy_classes_Bcs_bca_bba_java part_2 (1).pdf
Vision academy classes_bcs_bca_bba_java part_2
Chapter i(introduction to java)

More from DEVTYPE (20)

PDF
Рукописные лекции по линейной алгебре
PDF
1.4 Точечные оценки и их свойства
PDF
1.3 Описательная статистика
PDF
1.2 Выборка. Выборочное пространство
PDF
Continuity and Uniform Continuity
PDF
Coin Change Problem
PDF
Recurrences
PPT
D-кучи и их применение
PDF
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
PDF
ЖАДНЫЕ АЛГОРИТМЫ
PDF
Скорость роста функций
PDF
Asymptotic Growth of Functions
PDF
Кучи
PDF
Кодирование Хаффмана
PDF
Жадные алгоритмы: введение
PDF
Разбор задач по дискретной вероятности
PDF
Разбор задач модуля "Теория графов ll"
PDF
Наибольший общий делитель
PDF
Числа Фибоначчи
PDF
О-символика
Рукописные лекции по линейной алгебре
1.4 Точечные оценки и их свойства
1.3 Описательная статистика
1.2 Выборка. Выборочное пространство
Continuity and Uniform Continuity
Coin Change Problem
Recurrences
D-кучи и их применение
Диаграммы Юнга, плоские разбиения и знакочередующиеся матрицы
ЖАДНЫЕ АЛГОРИТМЫ
Скорость роста функций
Asymptotic Growth of Functions
Кучи
Кодирование Хаффмана
Жадные алгоритмы: введение
Разбор задач по дискретной вероятности
Разбор задач модуля "Теория графов ll"
Наибольший общий делитель
Числа Фибоначчи
О-символика

Recently uploaded (20)

PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Nekopoi APK 2025 free lastest update
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
L1 - Introduction to python Backend.pptx
PDF
top salesforce developer skills in 2025.pdf
PDF
Cost to Outsource Software Development in 2025
PDF
System and Network Administraation Chapter 3
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
medical staffing services at VALiNTRY
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PPTX
Transform Your Business with a Software ERP System
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Nekopoi APK 2025 free lastest update
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Computer Software and OS of computer science of grade 11.pptx
Softaken Excel to vCard Converter Software.pdf
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
Design an Analysis of Algorithms II-SECS-1021-03
L1 - Introduction to python Backend.pptx
top salesforce developer skills in 2025.pdf
Cost to Outsource Software Development in 2025
System and Network Administraation Chapter 3
Digital Systems & Binary Numbers (comprehensive )
PTS Company Brochure 2025 (1).pdf.......
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
medical staffing services at VALiNTRY
Which alternative to Crystal Reports is best for small or large businesses.pdf
Transform Your Business with a Software ERP System
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf

2. Базовый синтаксис Java