Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion modules/33-data-types/41-data-types-basics/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Display the number `-0.304`.
Display on the screen the result of dividing the integers 3 by 2. Think about why the answer turned out this way?
70 changes: 26 additions & 44 deletions modules/33-data-types/41-data-types-basics/en/README.md
Original file line number Diff line number Diff line change
@@ -1,62 +1,44 @@
Programs work with different information. This can be text, numbers, dates, boolean values. Inside high-level programming languages, every value belongs to some type. For example, strings belong to the type *String*, and integers belong to the type *int*.

Data types in Java are divided into two important groups according to how variables of this type are related and the values stored in them.
Why are types needed? They protect the program from hard-to-catch errors. A type defines two things.

What will the following code output?
* Allowed values. For example, numbers in Java are divided into two groups. Integers belong to the type *int*, and rational (fractional) numbers to the type *double*. This division is related to the specifics of how the hardware works.
* A set of allowed operations. For example, the multiplication operation makes sense for integers. But it does not make sense for strings. Multiplying the word "mother" by the word "notepad" is nonsense.

```java
var a = 10;
var b = a;
a = 20;
System.out.print(b);
```

10 will be output, because with the assignment b = a, the number 10, which at this moment is contained in a, will be written into the variable b.

If you write
A programming language recognizes types. That is why Java will not allow multiplying a string by a string, but will allow multiplying an integer by another integer. The presence of types and such restrictions protects programs from accidental errors:

```java
var a = "string";
var b = a;
```text
"one" * "two"
Error:
bad operand types for binary operator '*'
first type: java.lang.String
second type: java.lang.String
```

- then the situation will be different.

#### Briefly

Primitive data types in Java:

- Strings in quotes
- The numbers `7`,` -198`, `0` and so on
## Numbers and strings belong to different types

In fact, there are more, but now let's talk only about them.
---

There are different ways to present data in programs.

There are **strings** - character sets in quotes like `"Hello, World!"`. There are **integers** - for example, `7`, `-198`, `0`. These are two different categories of information - two different **data types**.

The multiplication operation makes sense for integers but it does not make sense for strings: to multiply the word "mother" by the word "notepad" is nonsense.

**The data type determines what can be done with the elements of a specific set of information.**

A programming language recognizes types. Therefore, Java will not allow us to multiply a line by line (“multiply text by text”). But it will allow to multiply an integer by another integer. The presence of types and such restrictions in the language protects programs from random errors.

Unlike strings, numbers do not need to be wrapped in quotes. To print the number 5, just write:
How does Java understand what type of data it is dealing with? By the way the value is written. A number is written without quotes, while strings are always enclosed in double quotes. For example, the value `"234"` is considered a string, even though digits are written inside it:

```java
System.out.print(5);
System.out.println(5); // => 5
System.out.println("234"); // => 234
```

Note that the number `5` and the string `"5"` are completely different things, although the output of `println` for this data is identical.
On the screen the result looks similar, but inside the program these are different values. The number `5` belongs to the type *int*, and `"234"` to the type *String*. Java will not let you add a string and a number directly without an explicit indication of how to convert the data.

Integers (`1`, `34`, `-19`, etc.) and rational numbers (`1.3`, `1.0`, `-14.324`, etc.) are two separate **types data**. This separation is associated with the characteristics of the device computers. **There are other types**, we will get to know them later.
## Primitive and reference types

Here is another example, but with a rational number:
Some types are built into the language. They are called primitive. Besides integers *int* and rational numbers *double*, they include the boolean type *boolean* with the values `true` and `false`, as well as the character type *char*:

```java
System.out.print(10.234);
int n = 5; // integer
double x = 1.5; // rational number
boolean flag = true; // boolean value
char c = 'A'; // one character
```

The lines in programming are called "strings", and the lines of text files are called "lines". For example, the code above has one line (lines), and there are no lines (strings). In all the lessons we will say **string** to indicate the data type "string", and **line** to indicate lines (lines) in files).
Pay attention to the type *char*. A character is written in single quotes, for example `'A'`. But a string of one character is enclosed in double quotes, for example `"A"`. These are different values of different types.

The type *String* belongs to reference types and describes a set of characters, that is, text. At the same time, strings are used on par with primitive types.

Programmers themselves can create new data types, albeit with certain restrictions.
There are many data types in Java, plus you can create your own. Gradually we will get to know all the necessary ones and learn to use them correctly.
16 changes: 15 additions & 1 deletion modules/33-data-types/41-data-types-basics/en/data.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
---
name: Data Types
name: Why data types are needed
tips:
- >
[Literal](https://en.wikipedia.org/wiki/Literal_(computer_programming))
- |
[Article on fractional numbers](https://habrahabr.ru/post/112953/)
definitions:
- name: Data type
description: >-
a set of data in code (a kind of information). A type defines what
can be done with the elements of a particular set. For example, integers,
rational numbers, and strings are different data types.
- name: Primitive data types
description: basic types built into the programming language itself.
- name: String
description: >
a data type that describes a set of characters (in other words, text), for
example `"text"`. In Java, strings are written in double quotes.
2 changes: 1 addition & 1 deletion modules/33-data-types/41-data-types-basics/es/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Muestra en pantalla el resultado de dividir los números enteros 3 entre 2. ¿Por qué se obtuvo ese resultado?
Muestra en pantalla el resultado de dividir los números enteros 3 entre 2. Piensa por qué se obtuvo esa respuesta.
46 changes: 29 additions & 17 deletions modules/33-data-types/41-data-types-basics/es/README.md
Original file line number Diff line number Diff line change
@@ -1,32 +1,44 @@
Dentro de los lenguajes de programación de alto nivel, los datos se dividen en tipos. Por ejemplo, las cadenas de texto se clasifican como *String*, mientras que los números se clasifican como *int*.
Los programas trabajan con información diferente. Puede ser texto, números, fechas, valores lógicos. Dentro de los lenguajes de programación de alto nivel, cada valor pertenece a algún tipo. Por ejemplo, las cadenas pertenecen al tipo *String*, y los números enteros al tipo *int*.

Check notice on line 1 in modules/33-data-types/41-data-types-basics/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/33-data-types/41-data-types-basics/es/README.md#L1

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/33-data-types/41-data-types-basics/es/README.md:1:177: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

¿Para qué sirven los tipos de datos? Para proteger el programa de errores difíciles de detectar. Los tipos de datos determinan dos cosas:
¿Para qué sirven los tipos? Protegen el programa de errores difíciles de detectar. Un tipo define dos cosas.

* Valores permitidos. Por ejemplo, en Java, los números se dividen en dos grupos de tipos: enteros (*int*) y racionales (*float*). Esta división está relacionada con las características técnicas del hardware.
* Conjunto de operaciones permitidas. Por ejemplo, la operación de multiplicación tiene sentido para el tipo "números enteros". Pero no tiene sentido para el tipo "cadena de texto": multiplicar la palabra "mamá" por la palabra "cuaderno" no tiene sentido.
* Valores permitidos. Por ejemplo, los números en Java se dividen en dos grupos. Los números enteros pertenecen al tipo *int*, y los racionales (decimales) al tipo *double*. Esta división está relacionada con las particularidades del funcionamiento del hardware.

Check notice on line 5 in modules/33-data-types/41-data-types-basics/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/33-data-types/41-data-types-basics/es/README.md#L5

If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE) Suggestions: `Java SE` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US Category: CASING
Raw output
modules/33-data-types/41-data-types-basics/es/README.md:5:41: If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE)
 Suggestions: `Java SE`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US
 Category: CASING
* Un conjunto de operaciones permitidas. Por ejemplo, la operación de multiplicación tiene sentido para los números enteros. Pero no tiene sentido para las cadenas. Multiplicar la palabra "mamá" por la palabra "cuaderno" es un sinsentido.

El lenguaje de programación reconoce los tipos. Por lo tanto, Java no nos permitirá multiplicar una cadena de texto por otra cadena de texto. Pero nos permitirá multiplicar un número entero por otro número entero. La presencia de tipos y de tales restricciones en el lenguaje protege los programas de errores accidentales:
El lenguaje de programación reconoce los tipos. Por eso Java no permitirá multiplicar una cadena por una cadena, pero sí permitirá multiplicar un número entero por otro número entero. La presencia de tipos y de tales restricciones protege los programas de errores accidentales:

```text
"uno" * "dos"
"one" * "two"
Error:
tipos de operandos incorrectos para el operador binario '*'
primer tipo: java.lang.String
segundo tipo: java.lang.String
bad operand types for binary operator '*'
first type: java.lang.String
second type: java.lang.String
```

¿Cómo sabe Java qué tipo de datos tiene delante? Cada valor se inicializa en algún lugar. Dependiendo de la forma de inicialización, se entiende qué es exactamente lo que tenemos delante.
## Los números y las cadenas pertenecen a tipos diferentes

Por ejemplo, un número es simplemente un número, no está envuelto entre comillas u otros caracteres emparejados. Pero las cadenas de texto siempre están delimitadas por comillas dobles. Por ejemplo, el valor `"234"` se considera una cadena de texto, aunque dentro de ella se escriban números:
¿Cómo entiende Java qué tipo de datos tiene delante? Por la forma en que se escribe el valor. Un número se escribe sin comillas, mientras que las cadenas siempre están delimitadas por comillas dobles. Por ejemplo, el valor `"234"` se considera una cadena, aunque dentro estén escritos dígitos:

```java
// El compilador entiende que aquí hay un número
var edad = 33;
System.out.println(5); // => 5
System.out.println("234"); // => 234
```

En inglés, las cadenas de texto en programación se llaman *strings*, mientras que las líneas de los archivos de texto se llaman *lines*. Por ejemplo, en el código anterior hay una línea (*line*) y cero cadenas (*strings*). En el idioma ruso, a veces puede haber confusión, por lo tanto, en todas las lecciones utilizaremos los siguientes términos:
En la pantalla el resultado se ve parecido, pero dentro del programa son valores diferentes. El número `5` pertenece al tipo *int*, y `"234"` al tipo *String*. Java no te dejará sumar una cadena y un número directamente sin una indicación explícita de cómo convertir los datos.

* **Cadena de texto** - para denotar el tipo de datos *strings*
* **Línea** - para denotar *lines* (líneas en archivos de texto)
## Tipos primitivos y de referencia

Hay muchos tipos de datos en Java, y también se pueden crear tipos personalizados. Gradualmente nos familiarizaremos con todos los necesarios y aprenderemos a usarlos correctamente.
Una parte de los tipos está integrada en el lenguaje. Se les llama primitivos. Además de los números enteros *int* y los racionales *double*, incluyen el tipo lógico *boolean* con los valores `true` y `false`, así como el carácter *char*:

Check notice on line 31 in modules/33-data-types/41-data-types-basics/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/33-data-types/41-data-types-basics/es/README.md#L31

Did you mean “less” instead of the French article “les”? (LES_LESS[2]) Suggestions: `less` URL: https://languagetool.org/insights/post/less-vs-least-grammar/#when-to-use-%E2%80%9Cless%E2%80%9D Rule: https://community.languagetool.org/rule/show/LES_LESS?lang=en-US&subId=2 Category: CONFUSED_WORDS
Raw output
modules/33-data-types/41-data-types-basics/es/README.md:31:20: Did you mean “less” instead of the French article “les”? (LES_LESS[2])
 Suggestions: `less`
 URL: https://languagetool.org/insights/post/less-vs-least-grammar/#when-to-use-%E2%80%9Cless%E2%80%9D 
 Rule: https://community.languagetool.org/rule/show/LES_LESS?lang=en-US&subId=2
 Category: CONFUSED_WORDS

```java
int n = 5; // número entero
double x = 1.5; // número racional
boolean flag = true; // valor lógico
char c = 'A'; // un carácter
```

Presta atención al tipo *char*. Un carácter se escribe entre comillas simples, por ejemplo `'A'`. En cambio, una cadena de un solo carácter se encierra entre comillas dobles, por ejemplo `"A"`. Son valores diferentes de tipos diferentes.

Check notice on line 40 in modules/33-data-types/41-data-types-basics/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/33-data-types/41-data-types-basics/es/README.md#L40

Possible spelling mistake found. (EN_MULTITOKEN_SPELLING_TWO[2]) Suggestions: `El Topo` Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=2 Category: MULTITOKEN_SPELLING
Raw output
modules/33-data-types/41-data-types-basics/es/README.md:40:192: Possible spelling mistake found. (EN_MULTITOKEN_SPELLING_TWO[2])
 Suggestions: `El Topo`
 Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=2
 Category: MULTITOKEN_SPELLING

El tipo *String* pertenece a los tipos de referencia y describe un conjunto de caracteres, es decir, texto. Al mismo tiempo, las cadenas se usan al mismo nivel que los tipos primitivos.

Hay muchos tipos de datos en Java, y además se pueden crear los propios. Poco a poco nos familiarizaremos con todos los necesarios y aprenderemos a usarlos correctamente.

Check notice on line 44 in modules/33-data-types/41-data-types-basics/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/33-data-types/41-data-types-basics/es/README.md#L44

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/33-data-types/41-data-types-basics/es/README.md:44:96: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC
16 changes: 16 additions & 0 deletions modules/33-data-types/41-data-types-basics/es/data.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
---
name: ¿Para qué sirven los tipos de datos?
tips:
- >
[Literal](https://es.wikipedia.org/wiki/Constante_(inform%C3%A1tica))
- |
[Artículo sobre números decimales](https://habrahabr.ru/post/112953/)
definitions:
- name: Tipo de datos
description: >-
un conjunto de datos en el código (una variedad de información). El tipo
define qué se puede hacer con los elementos de un conjunto concreto. Por
ejemplo, los números enteros, los números racionales y las cadenas son
tipos de datos diferentes.
- name: Tipos de datos primitivos
description: tipos básicos integrados en el propio lenguaje de programación.
- name: Cadena (string)
description: >
tipo de datos que describe un conjunto de caracteres (en otras palabras,
texto), por ejemplo `"text"`. En Java, las cadenas se escriben entre
comillas dobles.
2 changes: 1 addition & 1 deletion modules/33-data-types/45-explicit-types/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Display the number `-0.304`.
Create the string *One more time* with an explicit type specification and print it to the screen.
70 changes: 35 additions & 35 deletions modules/33-data-types/45-explicit-types/en/README.md
Original file line number Diff line number Diff line change
@@ -1,62 +1,62 @@

Data types in Java are divided into two important groups according to how variables of this type are related and the values stored in them.

What will the following code output?
Until now, when defining variables, we used the keyword `var`. This may surprise those who already have experience with Java. Usually the definition of variables is shown like this:

```java
var a = 10;
var b = a;
a = 20;
System.out.print(b);
int x = 3;
String greeting = "Hello Hexlet!";
```

10 will be output, because with the assignment b = a, the number 10, which at this moment is contained in a, will be written into the variable b.
The time has come to reveal the cards. Java is a statically typed language. In such languages, the type of a variable is fixed at its declaration and does not change until the end of the program. The type is specified before the variable name. In the example above, this is an integer (*int*) and a string (*String*).

Check notice on line 8 in modules/33-data-types/45-explicit-types/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/33-data-types/45-explicit-types/en/README.md#L8

If ‘type’ is a classification term, ‘a’ is not necessary. Use “type of”. (The phrases ‘kind of’ and ‘sort of’ are informal if they mean ‘to some extent’.) (KIND_OF_A[1]) Suggestions: `type of` Rule: https://community.languagetool.org/rule/show/KIND_OF_A?lang=en-US&subId=1 Category: GRAMMAR
Raw output
modules/33-data-types/45-explicit-types/en/README.md:8:99: If ‘type’ is a classification term, ‘a’ is not necessary. Use “type of”. (The phrases ‘kind of’ and ‘sort of’ are informal if they mean ‘to some extent’.) (KIND_OF_A[1])
 Suggestions: `type of`
 Rule: https://community.languagetool.org/rule/show/KIND_OF_A?lang=en-US&subId=1
 Category: GRAMMAR

## The type is specified explicitly and does not change

If you write
In a statically typed language, every variable has a type, and it is fixed. If a variable is declared as *int*, then only an integer can be put into it:

```java
var a = "string";
var b = a;
int n = 5;
double x = 1.5;
boolean flag = true;
char c = 'A';
String s = "hi";
```

- then the situation will be different.

#### Briefly

Primitive data types in Java:
An attempt to put a value of another type into a variable leads to an error. A string cannot be assigned to a variable of type *int*:

- Strings in quotes
- The numbers `7`,` -198`, `0` and so on

In fact, there are more, but now let's talk only about them.
---
```java
// Error: incompatible types: java.lang.String cannot be converted to int

Check notice on line 25 in modules/33-data-types/45-explicit-types/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/33-data-types/45-explicit-types/en/README.md#L25

Possible typo: you repeated a word (ENGLISH_WORD_REPEAT_RULE) Suggestions: `int` Rule: https://community.languagetool.org/rule/show/ENGLISH_WORD_REPEAT_RULE?lang=en-US Category: MISC
Raw output
modules/33-data-types/45-explicit-types/en/README.md:25:70: Possible typo: you repeated a word (ENGLISH_WORD_REPEAT_RULE)
 Suggestions: `int`
 Rule: https://community.languagetool.org/rule/show/ENGLISH_WORD_REPEAT_RULE?lang=en-US
 Category: MISC
int ops = "test";
```

There are different ways to present data in programs.
## When types are checked

There are **strings** - character sets in quotes like `"Hello, World!"`. There are **integers** - for example, `7`, `-198`, `0`. These are two different categories of information - two different **data types**.
Java checks types in advance, even before the program runs, at the compilation stage. The compiler reads the code, checks the types of values and operations, and refuses to build the program if it finds a mismatch. That is why we will see the error from the example above before the program starts working.

The multiplication operation makes sense for integers but it does not make sense for strings: to multiply the word "mother" by the word "notepad" is nonsense.
In this, Java differs from languages with dynamic typing, where types are checked while the program is running. In such languages, a type mismatch error surfaces only at the moment the appropriate line of code executes. Static checking catches some errors earlier and helps not to carry them all the way to the user.

**The data type determines what can be done with the elements of a specific set of information.**
Explicit type specification has a second advantage as well. The type next to the variable name works as a hint for whoever reads the code. From the line `int count = 0;` it is immediately clear that the variable stores an integer. Java takes control of types upon itself, and the code becomes clearer for people.

A programming language recognizes types. Therefore, Java will not allow us to multiply a line by line (“multiply text by text”). But it will allow to multiply an integer by another integer. The presence of types and such restrictions in the language protects programs from random errors.
## When Java casts types itself

Unlike strings, numbers do not need to be wrapped in quotes. To print the number 5, just write:
Sometimes values of different numeric types appear in one expression. If you add an integer and a rational number, Java itself casts the integer to a rational one:

```java
System.out.print(5);
double result = 1 + 1.5;
System.out.println(result); // => 2.5
```

Note that the number `5` and the string `"5"` are completely different things, although the output of `println` for this data is identical.
The integer `1` turns into `1.0`, and the result comes out as `2.5`. This happens because any integer can be represented exactly as a rational number, and no data is lost. But Java will not mix a string and a number by itself. For that, an explicit conversion is needed, and we will learn to do it.

Integers (`1`, `34`, `-19`, etc.) and rational numbers (`1.3`, `1.0`, `-14.324`, etc.) are two separate **types data**. This separation is associated with the characteristics of the device computers. **There are other types**, we will get to know them later.
## Type inference and the word var

Here is another example, but with a rational number:
Earlier in Java variables were created only with an explicit type specification, until the word `var` appeared. This is a special keyword that turns on the mechanism of **type inference**. Type inference itself determines the type of the assigned value and binds it to the variable:

```java
System.out.print(10.234);
// The compiler understands that this is an integer
var age = 33;

// And this is a string
var name = "Tom";
```

The lines in programming are called "strings", and the lines of text files are called "lines". For example, the code above has one line (lines), and there are no lines (strings). In all the lessons we will say **string** to indicate the data type "string", and **line** to indicate lines (lines) in files).
Type inference appeared in Java in 2018, although in some other languages it has existed for several decades. The first language with type inference is called ML, and it appeared as early as 1973. Since then, type inference has been added to OCaml, Haskell, C#, F#, Kotlin, Scala, and many other languages.

Programmers themselves can create new data types, albeit with certain restrictions.
The word `var` does not cancel static typing. The variable still has a type; the compiler infers it. After that the type is just as fixed, and you will not be able to put a value of another type into such a variable. Type inference is preferable in most situations. It happens that the inferred type does not suit us, and then the type is specified explicitly.
13 changes: 12 additions & 1 deletion modules/33-data-types/45-explicit-types/en/data.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,16 @@
---
name: Data Types
name: Explicit typing
tips:
- |
[Typing](https://en.wikipedia.org/wiki/Strong_and_weak_typing)
- |
[Article on fractional numbers](https://habrahabr.ru/post/112953/)
definitions:
- name: Static typing
description: >-
an approach in which the type of a variable is fixed at its declaration and
is checked in advance, at the compilation stage, before the program runs.
- name: Type inference
description: >-
a mechanism that itself determines the type of the assigned value and binds
it to the variable. In Java it is turned on with the keyword `var`.
Loading
Loading