Variables and Data Types

Intro

Problem

Как с помощью языка программирования хранить информацию в оперативной памяти?

Solution

  • Data types

  • Variables

Variables

Variables

  • Variable (переменная) - это именованная ячейка памяти.

  • Variable содержит в себе какое-то value (значение).

  • Value в variable может изменяться в процессе выполнения программы.

Variables and memory

Variables in Java

Terminologies

Decralation

Example

int x; // объявление переменной
x = 10; // инициализация переменной
x = 21; // присваивание значения переменной
System.out.println(x);
Output
21

Example

int y = 10; // объявление и инициализация переменной
x = 21; // присваивание значения переменной
System.out.println(y);
Output
21

Example

int z; // объявление переменной
System.out.println(z);

Compile error: java: variable z might not have been initialized

Example

int x, y;
x = 10;
y = 25;
System.out.println(x); // 10
System.out.println(y); // 25
Output
10
25

Bad practice

Example

int a = 8, b = 15;
System.out.println(a);
System.out.println(b);
Output
8
15

Bad practice

Example

int i = 1;
int j = 11;
System.out.println(i);
System.out.println(j);
Output
1
11

Good practice

Identifier

Variables

  • При объявлении переменной:

    • сначала указывается data type (тип данных) переменной

    • затем identifier (идентификатор) задаваемой переменной

    • например: int age.

Identifiers

  • Identifiers (идентификаторы) – это имена, которые даются различным элементам языка для упрощения доступа к ним.

  • Identifiers регистрозависимые, т.е. AGE и age совершенно разные identifiers

  • Identifiers должны быть УНИКАЛЬНЫ в рамках текущего блока

Identifiers for variables

В именах переменных разрешено использовать символы:

  • A-Z

  • a-z

  • 0-9

  • $, _

Identifiers for variables

В именах переменных запрещено применение:

  • цифры в качестве первого символа

  • ТОЛЬКО одного символа _ (error: as of release 9, '_' is a keyword, and may not be used as an identifier)

Identifiers

PossibleImpossible

my$money

field#

_flag

_

newString2

1searchIndex

Code Convention

  • Как правило:

    • Переменные именуются с использованием camelCase.

    • Название должно объяснять что за значение находится в переменной.

Example

int cargo = 11;
int carryingCapacity = 2;
int depositAmount = 1500;
int depositYears = 5;
int depositAnnualPercentage = 3;

Data Types

Data Types

Data Types

Data Types size

Data Types

Integer

ТипРазмерМинМакс

byte

1 byte

-128

127

short

2 bytes

-32 768

32 767

int

4 bytes

-2 147 483 648

2 147 483 647

long

8 bytes

-9 223 372 036 854 775 808

9 223 372 036 854 775 807

Integer

ТипРазмерМинМакс

byte

1 byte

-27

27 - 1

short

2 bytes

-215

215 - 1

int

4 bytes

-231

231 - 1

long

8 bytes

-263

263 - 1

Floating Point

ТипРазмерОписание

float

4 bytes

Single-precision 32-bit IEEE 754 floating point

double

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)

Floating Point

ТипРазмерОписание

float

4 bytes

Single precision: log10(224), which is about 7~8 decimal digits

double

8 bytes

Double precision: log10(253), which is about 15~16 decimal digits

Boolean

ТипРазмерМинМакс

boolean

1 bit

false

true

Character

ТипРазмерМинМакс

char

2 bytes

\u0000 (Unicode)

\uffff (Unicode)

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

ТипРазмерМинМакс

char

2 bytes

0 (as Integer)

65 535 (as Integer)

Literals

Literals

  • Literals (литералы) — это явно заданные значения в исходном коде программы.

Example

class Example {
    public static void main(String[] args) {
        System.out.println("Hello world!");
    }
}

Types of Literals

Types of Literals

Integer Literal

  • All integer values are integer literals

  • For big integer values use suffix l OR L

Example

int i = 1234567;
// long a = 12345678901; // error: integer number too large
long b = 12345678901L;
long c = 12345678901l; // Not recommend. Use `L`
1234567
12345678901
12345678901

Types of Integer Literals

Types of Integer Literals

Integer Literal

  • 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

Integer Literal

  • 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

Example

int decimalNumber = 42;
int binaryNumber = 0b101010;
int octalNumber = 052;
int hexadecimalNumber = 0x2A;
42
42
42
42

Floating point Literal

  • 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)

Example

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

Example

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

Example

// 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 Literals

  • Cannot 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

Example

int a = 123456789;
int b = 123_456_789;
int c = 123___456______789;
double d = 0.123_456_789;
123456789
123456789
123456789
0.123456789

Character Literal

  • start with '

  • contains ONE char without symbols: \, '

  • end with '

Example

char c1 = 'A';
A

String Literal

  • start with "

  • contains chars without symbols: \, "

  • end with "

Example

String text = "text literal";
text literal

Escape Sequences with \

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

Example

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 Sequences with \

Escape SequenceUnicodeDescription

\b

\u0008

Backspace

\t

\u0009

Horizontal tab

\n

\u000a

Linefeed

\f

\u000c

Form feed

\r

\u000d

Carriage return

\"

\u0022

Double quotation mark - "

\'

\u0027

Single quotation mark - '

\\

\u005c

Backslash - \

Octal Character Literals

Octal LiteralUnicodeDescription

\041

\u0021

!

\101

\u0041

A

\141

\u0061

a

\071

\u0039

9

\042

\u0022

Double quotation mark

Caution

  • Don’t use the Unicode format to express an end-of-line character.

  • Use the \n or \r characters instead.

Example

System.out.print("text\ntext");
// System.out.print("\u000a"); // a compiler error;
// System.out.print('\u000a'); // a compiler error;
text
text

Array literals

  • start with {

  • contains values separated with , (comma)

  • end with }

Example

int[] ages = {15, 45, 34, 67, 89};
Point[] points = {new Point(1.0, 2.1), new Point(-3.4, 5.1)}

Boolean literals

  • true

  • false

  • But they are keywords

Example

boolean enabled = false;
boolean isRun = true;
false
true

Literal null

  • null represent a void reference

  • null is a pointer to nothing

  • But null is keyword

Example

String text = null;
null

Constants

Constants

  • Кроме переменных, в Java для хранения данных можно использовать константы.

  • Константы позволяют задать такие переменные, которые не должны больше изменяться.

  • В отличие от переменных константам можно присвоить значение ТОЛЬКО один раз.

  • Объявляется, как и переменные, но только со служебным словом final.

Code Convention

  • Как правило:

    • Константы именуются с использованием UPPER_SNAKE_CASE.

    • Название константы должно объяснять, что за значение находится в ней.

Code Convention

final int LIMIT = 5;
final String NUMBER_SYSTEM = "BINARY";

Type Casting

Преобразование типов

  • Widening Casting (automatically)

  • Narrowing Casting (manually)

Преобразование типов

Type casting

Examples: Widening Casting

short a = 'Z';
System.out.println(a); // 90
double b = 1_234_567_890_123_456L;
System.out.println(b); // 1.234567890123456E15

Examples: Widening Casting with lossy

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

Examples: Narrowing Casting

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

Java

  • Java - строго типизированный язык программирования.

  • Типы переменных должны быть известны до compile time

  • (@since 10) или могут ОДНОЗНАЧНО установлены во время compile time

Why char uses 2 byte in java and what is \u0000 ?

  • It is because java uses Unicode system not ASCII code system.

  • The \u0000 is the lowest range of Unicode system.