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
5 changes: 4 additions & 1 deletion modules/30-variables/10-definition/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
  Create a variable with the name `motto` and the contents of `What is Dead May Never Die!`. Print the contents of the variable.
Create a variable named `motto` with the contents `What Is Dead May Never Die!`. Print the contents of the variable.
```text
What Is Dead May Never Die!
```
120 changes: 103 additions & 17 deletions modules/30-variables/10-definition/en/README.md
Original file line number Diff line number Diff line change
@@ -1,39 +1,125 @@
Imagine the task, we need to print the phrase _Father!_ On the screen twice or even five times. This problem can be solved in the forehead:
Imagine you need to print the phrase *Father!* twice:

```java
System.out.print("Father!");
System.out.print("Father!");
System.out.println("Father!");
System.out.println("Father!");
```

In the simplest case, this is what you should do, but if the phrase _Father!_ Begins to be used more often, and even in different parts of the program, you will have to repeat it everywhere. Problems with this approach will begin when you need to change our phrase, and this happens quite often. We will have to find all the places where the phrase _Father!_ Was used and perform the necessary replacement. And you can do differently. Instead of copying our expression, just create a variable with this phrase.
This approach works if the phrase appears only a couple of times. But what if it is used often, in different parts of the program? Then you would have to copy the same expression over and over.

And what if the phrase needs to be changed, for example to replace *Father!* with *Mother!*? You would have to find and fix every occurrence by hand. This is inconvenient and leads to errors.

## Variables

To avoid duplicating the same string, you can store it in a variable and print its contents:

```java
//greeting - translated as greeting
var greeting = "Father!";
System.out.print(greeting);
System.out.print(greeting);
```

In the `var greeting = "Father!"` - the value of `"Father!"` is assigned to a variable of type String named `greeting`.
System.out.println(greeting);
System.out.println(greeting);
```

When the variable is created, you can start using it. It is substituted in those places where our phrase used to stand. During code execution, the line `System.out.print(greeting)` replaces the variable with its contents, and then the code is executed. As a result, the output of our program will be as follows:
Result:

```text
Father!
Father!
```

For the name of the variable, any set of valid characters is used, which include letters of the English alphabet, numbers and the underscore character `_`. In this case, the number can not be put at the beginning. Variable names are case-sensitive, that is, the name `hello` and the name `heLLo` are two different names, and therefore two variables.
A **variable** is a name behind which a value is stored. In this example, we created a variable named `greeting` and wrote the string `"Father!"` into it.

```text
var greeting = "Father!";

Variable Value
┌──────────┐ ┌──────────┐

Check notice on line 36 in modules/30-variables/10-definition/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/en/README.md#L36

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/30-variables/10-definition/en/README.md:36:49: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION

Check notice on line 36 in modules/30-variables/10-definition/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/en/README.md#L36

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/30-variables/10-definition/en/README.md:36:57: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION
│ greeting │ ──→ │ "Father!"│
└──────────┘ └──────────┘

Check notice on line 38 in modules/30-variables/10-definition/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/en/README.md#L38

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/30-variables/10-definition/en/README.md:38:26: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION
```

The line `var greeting = "Father!"` reads like this: "take the value `"Father!"` and assign it to the variable named `greeting`". The `=` sign here works as an assignment operator, not as a sign of equality like in mathematics. It puts the value into the variable.

Check notice on line 41 in modules/30-variables/10-definition/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/en/README.md#L41

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/30-variables/10-definition/en/README.md:41:17: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION

The keyword `var` tells the compiler that we are creating a new variable. Java itself determines the type of the variable by the value we wrote into it. Since there is a string `"Father!"` on the right, the variable `greeting` becomes a string variable.

When we write `System.out.println(greeting)`, the program substitutes the value stored in it for the name `greeting`. As a result, the string `Father!` is printed to the screen.

```text
System.out.println(greeting);
|
v
System.out.println("Father!");
```

## Types of variables

In Java, every variable has a type. The type says what kind of data is stored inside the variable. An integer, a floating-point number, or a string define different types:

The number of variables created is not limited in any way; large programs contain tens and hundreds of thousands of variable names:
```java
var age = 25; // integer
var price = 9.99; // floating-point number
var name = "Tom"; // string
```

In the examples above, the type is determined automatically by the value to the right of the `=` sign. You can also specify the type explicitly, then instead of `var` you write the name of the type:

```java
int age = 25;
double price = 9.99;
String name = "Tom";
```

Both ways create a variable with the same result. Writing it with `var` is shorter, so we will use it in the examples.

Check notice on line 72 in modules/30-variables/10-definition/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/en/README.md#L72

A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1]) Suggestions: `Java,` URL: http://englishplus.com/grammar/00000074.htm Rule: https://community.languagetool.org/rule/show/MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE?lang=en-US&subId=1 Category: PUNCTUATION
Raw output
modules/30-variables/10-definition/en/README.md:72:77: A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1])
 Suggestions: `Java,`
 URL: http://englishplus.com/grammar/00000074.htm 
 Rule: https://community.languagetool.org/rule/show/MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE?lang=en-US&subId=1
 Category: PUNCTUATION

## Variable names

The programmer comes up with variable names. In Java you can use:

- Latin letters (a-z, A-Z),
- digits (but not at the beginning),
- underscore `_`.

Examples of valid names: `greeting`, `name1`, `helloWorld`. Java distinguishes between lowercase and uppercase letters. The variables `greeting`, `Greeting`, and `GREETING` will be three different variables.

Check notice on line 82 in modules/30-variables/10-definition/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/en/README.md#L82

A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1]) Suggestions: `code,` URL: http://englishplus.com/grammar/00000074.htm Rule: https://community.languagetool.org/rule/show/MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE?lang=en-US&subId=1 Category: PUNCTUATION
Raw output
modules/30-variables/10-definition/en/README.md:82:129: A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1])
 Suggestions: `code,`
 URL: http://englishplus.com/grammar/00000074.htm 
 Rule: https://community.languagetool.org/rule/show/MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE?lang=en-US&subId=1
 Category: PUNCTUATION

## Variables and literals

In code it is important to distinguish where we use a variable and where we write a value directly. This is especially noticeable in the example with `System.out.println()`:

```java
var greeting = "Mother!";
System.out.println(greeting); // => Mother!
System.out.println("greeting"); // => greeting
```

In the first case, the **variable** `greeting` is used, and the program substitutes its value. In the second case, `"greeting"` is enclosed in quotes, so it is a **string literal**, that is, a ready value written directly in the code. Although we see the word `greeting` in both cases, from the compiler's point of view these are different things.

Literals are data written explicitly (for example, `"Hello"`, `42`, `3.14`). Identifiers work as names of variables and methods (for example, `greeting`, `println`), which point to already existing values or commands.

## Several variables in a program

In one program you can create as many variables as you want. Each stores its own data and does not interfere with the others:

```java
var greeting1 = "Father!";
System.out.print(greeting1);
System.out.print(greeting1);
System.out.println(greeting1);
System.out.println(greeting1);

var greeting2 = "Mother!";
System.out.print(greeting2);
System.out.print(greeting2);
System.out.println(greeting2);
System.out.println(greeting2);
```

For the convenience of program analysis, it is customary to create variables as close as possible to the place where they are used.
Result:

```text
Father!
Father!
Mother!
Mother!
```

The number of variables depends on the logic of the program. The more complex the task, the more intermediate data has to be stored somewhere.

## Where to create variables

Programmers try to create variables closer to the place where they are used. This makes the code more readable. This is especially important in large programs, where there can be tens and hundreds of thousands of variables.
4 changes: 4 additions & 0 deletions modules/30-variables/10-definition/en/data.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ tips:
- >
[Naming in
programming](https://ru.hexlet.io/blog/posts/naming-in-programming?utm_source=code-basics&utm_medium=referral&utm_campaign=blog&utm_content=lesson)
definitions:
- name: Variable
description: >-
a way to store information and give it a name for later use in the code.
118 changes: 99 additions & 19 deletions modules/30-variables/10-definition/es/README.md
Original file line number Diff line number Diff line change
@@ -1,45 +1,125 @@
Imagina que tienes la tarea de imprimir en la pantalla la frase *¡Padre!* dos veces. Puedes resolver este problema de manera directa:
Imagina que necesitas imprimir la frase *Father!* dos veces:

```java
System.out.println("¡Padre!"); // => ¡Padre!
System.out.println("¡Padre!"); // => ¡Padre!
System.out.println("Father!");
System.out.println("Father!");
```

En el caso más simple, esto funciona bien. Sin embargo, si la frase *¡Padre!* se utiliza con más frecuencia y en diferentes partes del programa, tendrás que repetirla en todas partes. Los problemas con este enfoque surgirán cuando necesites cambiar la frase, lo cual ocurre con bastante frecuencia. Tendrás que encontrar todos los lugares donde se utilizó la frase *¡Padre!* y realizar el reemplazo necesario. Pero hay otra forma de hacerlo. En lugar de copiar nuestra expresión, simplemente crea una variable con esta frase:
Este enfoque sirve si la frase aparece solo un par de veces. Pero ¿qué pasa si se usa con frecuencia, en diferentes partes del programa? Entonces tendrías que copiar la misma expresión una y otra vez.

¿Y qué pasa si hay que cambiar la frase, por ejemplo reemplazar *Father!* por *Mother!*? Tendrías que buscar y corregir todas las apariciones a mano. Esto es incómodo y provoca errores.

## Variables

Para no duplicar la misma cadena, puedes guardarla en una variable e imprimir su contenido:

```java
// greeting - se traduce como saludo
// var - solo se necesita al definir la variable
var greeting = "¡Padre!";
var greeting = "Father!";

System.out.println(greeting);
System.out.println(greeting);
```

En la línea `var greeting = "¡Padre!"`, se asigna el valor `"¡Padre!"` a la variable con el nombre `greeting`.
Resultado:

Una vez que se crea la variable, puedes comenzar a usarla. Se inserta en los lugares donde solía estar nuestra frase. Durante la ejecución del código, en la línea `System.out.println(greeting)`, el contenido de la variable se inserta en lugar de la variable misma, y luego se ejecuta el código. Como resultado, la salida de nuestro programa será la siguiente:
```text
Father!
Father!
```

Una **variable** es un nombre tras el cual se guarda un valor. En este ejemplo creamos una variable llamada `greeting` y escribimos en ella la cadena `"Father!"`.

```text
¡Padre!
¡Padre!
var greeting = "Father!";

Variable Valor
┌──────────┐ ┌──────────┐

Check notice on line 36 in modules/30-variables/10-definition/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/es/README.md#L36

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/30-variables/10-definition/es/README.md:36:41: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION

Check notice on line 36 in modules/30-variables/10-definition/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/es/README.md#L36

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/30-variables/10-definition/es/README.md:36:49: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION
│ greeting │ ──→ │ "Father!"│
└──────────┘ └──────────┘

Check notice on line 38 in modules/30-variables/10-definition/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/es/README.md#L38

Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES) URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US Category: PUNCTUATION
Raw output
modules/30-variables/10-definition/es/README.md:38:13: Unpaired symbol: ‘"’ seems to be missing (EN_UNPAIRED_QUOTES)
 URL: https://languagetool.org/insights/post/punctuation-guide/#what-are-parentheses 
 Rule: https://community.languagetool.org/rule/show/EN_UNPAIRED_QUOTES?lang=en-US
 Category: PUNCTUATION
```

Para el nombre de la variable, se puede utilizar cualquier conjunto de caracteres válidos, que incluyen letras del alfabeto inglés, números y el guión bajo `_`. Sin embargo, no se puede colocar un número al principio. Los nombres de las variables distinguen entre mayúsculas y minúsculas, es decir, `hello` y `heLLo` son dos nombres diferentes y dos variables diferentes. A continuación se muestra un ejemplo con dos variables diferentes:
La línea `var greeting = "Father!"` se lee así: "toma el valor `"Father!"` y asígnalo a la variable llamada `greeting`". El signo `=` funciona aquí como un operador de asignación, no como una señal de igualdad como en matemáticas. Coloca el valor dentro de la variable.

La palabra clave `var` le indica al compilador que estamos creando una nueva variable. Java determina por sí misma el tipo de la variable según el valor que escribimos en ella. Como a la derecha hay una cadena `"Father!"`, la variable `greeting` se convierte en una variable de cadena.

Cuando escribimos `System.out.println(greeting)`, el programa sustituye el nombre `greeting` por el valor que se almacena en ella. Como resultado, en la pantalla se imprime la cadena `Father!`.

```text
System.out.println(greeting);
|

Check notice on line 49 in modules/30-variables/10-definition/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/es/README.md#L49

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/30-variables/10-definition/es/README.md:49:12: 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
v
System.out.println("Father!");
```

## Tipos de variables

En Java, cada variable tiene un tipo. El tipo indica qué datos se almacenan dentro de la variable. Un número entero, un número decimal o una cadena definen tipos diferentes:

```java
var greeting1 = "¡Padre!";
var age = 25; // número entero
var price = 9.99; // número decimal
var name = "Tom"; // cadena
```

En los ejemplos anteriores, el tipo se determina automáticamente según el valor a la derecha del signo `=`. También se puede indicar el tipo de forma explícita, entonces en lugar de `var` se escribe el nombre del tipo:

```java
int age = 25;
double price = 9.99;
String name = "Tom";
```

Ambas formas crean una variable con el mismo resultado. La escritura con `var` es más corta, por eso la usaremos en los ejemplos.

Check notice on line 72 in modules/30-variables/10-definition/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/es/README.md#L72

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/30-variables/10-definition/es/README.md:72:91: 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

## Nombres de las variables

Los nombres de las variables los inventa el propio programador. En Java se pueden usar:

- letras latinas (a-z, A-Z),
- dígitos (pero no al principio),
- guion bajo `_`.

Ejemplos de nombres válidos: `greeting`, `name1`, `helloWorld`. Java distingue entre letras minúsculas y mayúsculas. Las variables `greeting`, `Greeting` y `GREETING` serán tres variables diferentes.

## Variables y literales

En el código es importante distinguir dónde usamos una variable y dónde escribimos un valor directamente. Esto se nota especialmente en el ejemplo con `System.out.println()`:

```java
var greeting = "Mother!";
System.out.println(greeting); // => Mother!

Check notice on line 90 in modules/30-variables/10-definition/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/10-definition/es/README.md#L90

If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE) Suggestions: `El Segundo` 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/30-variables/10-definition/es/README.md:90:43: If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE)
 Suggestions: `El Segundo`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US
 Category: CASING
System.out.println("greeting"); // => greeting
```

En el primer caso se usa la **variable** `greeting`, y el programa sustituye su valor. En el segundo caso, `"greeting"` está entre comillas, por lo que es un **literal de cadena**, es decir, un valor listo escrito directamente en el código. Aunque vemos la palabra `greeting` en ambos casos, desde el punto de vista del compilador son cosas diferentes.

Los literales son datos escritos de forma explícita (por ejemplo, `"Hello"`, `42`, `3.14`). Los identificadores funcionan como nombres de variables y métodos (por ejemplo, `greeting`, `println`), que apuntan a valores o comandos ya existentes.

## Varias variables en un programa

En un mismo programa se pueden crear tantas variables como quieras. Cada una almacena sus propios datos y no interfiere con las demás:

```java
var greeting1 = "Father!";
System.out.println(greeting1);
System.out.println(greeting1);
var greeting2 = "¡Madre!";

var greeting2 = "Mother!";
System.out.println(greeting2);
System.out.println(greeting2);
```

Resultado:

```text
¡Padre!
¡Padre!
¡Madre!
¡Madre!
Father!
Father!
Mother!
Mother!
```

Para facilitar el análisis del programa, se recomienda crear variables lo más cerca posible del lugar donde se utilizan.
La cantidad de variables depende de la lógica del programa. Cuanto más compleja es la tarea, más datos intermedios hay que almacenar en algún lugar.

## Dónde crear las variables

Los programadores procuran crear las variables más cerca del lugar donde se usan. Esto hace que el código sea más legible. Esto es especialmente importante en programas grandes, donde puede haber decenas y cientos de miles de variables.
10 changes: 8 additions & 2 deletions modules/30-variables/10-definition/es/data.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
---
name: ¿Qué es una variable?
tips:
- |
[Nomenclatura en programación](https://codica.la/blog/naming-in-programming)
- >
[Nomenclatura en
programación](https://codica.la/blog/naming-in-programming)
definitions:
- name: Variable
description: >-
una forma de guardar información y darle un nombre para su uso posterior en
el código.
7 changes: 6 additions & 1 deletion modules/30-variables/12-change/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
The code defines a variable with the value `'Brienna'`. Redefine the value of this variable and assign it the same line, but upside down.

The code defines a variable with the value `"Brienna"`. Redefine the value of this variable and assign it the same value, but reversed.

```text
anneirB
```
50 changes: 42 additions & 8 deletions modules/30-variables/12-change/en/README.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,50 @@
The word "variable" itself suggests that its value can change. This is one of the main reasons why variables exist at all.

The word "variable" itself means that it can be changed. Indeed, over time within the program, the values of the variables may change.
Here is an example:

```java
// greeting - translated as greeting
var greeting = "Father!";
System.out.print(greeting);
System.out.print(greeting);
System.out.println(greeting); // => Father!

// var is no longer used, the variable is defined above
greeting = "Mother!";
System.out.print(greeting);
System.out.print(greeting);
System.out.println(greeting); // => Mother!
```

Here we first wrote one string (*Father!*) into the variable, and then another (*Mother!*). The name of the variable did not change, but the value inside became different. The keyword `var` is only needed when creating a variable. When changing the value, it is no longer written.

```text
Before: greeting ──→ "Father!"
After: greeting ──→ "Mother!"
```

## Why change a value

In real programs, variables change all the time. Here are a few reasons:

- The program reacts to the user's actions. For example, while you are entering data into a form on a website, the variables that hold this data are constantly changing.
- Intermediate results. Data often goes through a series of transformations, and at each stage the variable is updated with a new value. A similar mechanism exists even in calculators, when intermediate values are stored with the `m+` or `m-` keys.
- Storing state. If you are writing a game, then the position of the character, its health, the score, and the current level will be variables that change all the time.

Check notice on line 27 in modules/30-variables/12-change/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/12-change/en/README.md#L27

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/30-variables/12-change/en/README.md:27:165: 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 of a variable does not change

Java is a statically typed language. The type of a variable is set when it is created and never changes again. In the example above, we wrote a string when creating the variable. The compiler remembers the type and checks all subsequent changes.

Check notice on line 31 in modules/30-variables/12-change/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/30-variables/12-change/en/README.md#L31

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/30-variables/12-change/en/README.md:31:29: 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

If you try to assign a number to the same variable, we will get an error:

```java
greeting = 5;
// Error:
// incompatible types: int cannot be converted to java.lang.String
// incompatible types: a number cannot be turned into a string
```

The name remains the same, but inside the other data. It should be noted that when changing variables, the type of data contained in them cannot change (this is not quite the case for object-oriented programming, but for the time being we will not go into details). If a variable was assigned a string, then when compiling this assignment — even before the program was started — java associates the data type “string” with this variable, and knows that there will always be only strings, and will not let it put something else in it.
The compiler performs this check without running the code. That is exactly why this kind of typing is called **static**. In JavaScript, Ruby, PHP, Python, and other dynamic languages, such behavior is not considered an error, and a variable can change its type while the program runs.

## The downside of mutability

Variables give a way to store data that changes as the program runs. Thanks to this, you can write programs that behave differently depending on conditions, user actions, or the results of calculations.

But mutability has a downside too. Sometimes it is hard to understand what exactly is written into a variable at a particular moment in time. The developer has to track where and how it changed, especially if the code is long.

Variables are powerful, and at the same time dangerous thing. One can never be exactly sure what is written inside it without analyzing the code that is in front of the variable. This is exactly what the developers are doing during debugging, when they are trying to figure out why the program is not working or is not working as intended.
This is exactly what is done during debugging. The developer figures out why the program works differently than intended. They check the values of variables, track the order in which the code runs, and look for where something went wrong.
5 changes: 5 additions & 0 deletions modules/30-variables/12-change/en/data.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,7 @@
---
name: Variable change
tips: []
definitions:
- name: Variable
description: >-
a way to store information and give it a name for later use in the code.
Loading
Loading