diff --git a/modules/30-variables/10-definition/en/EXERCISE.md b/modules/30-variables/10-definition/en/EXERCISE.md index adcbe3f..3170e64 100644 --- a/modules/30-variables/10-definition/en/EXERCISE.md +++ b/modules/30-variables/10-definition/en/EXERCISE.md @@ -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! +``` diff --git a/modules/30-variables/10-definition/en/README.md b/modules/30-variables/10-definition/en/README.md index 253ccf3..fa2cff1 100644 --- a/modules/30-variables/10-definition/en/README.md +++ b/modules/30-variables/10-definition/en/README.md @@ -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 +┌──────────┐ ┌──────────┐ +│ greeting │ ──→ │ "Father!"│ +└──────────┘ └──────────┘ +``` + +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. + +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. + +## 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. + +## 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. diff --git a/modules/30-variables/10-definition/en/data.yml b/modules/30-variables/10-definition/en/data.yml index 929d714..440f986 100644 --- a/modules/30-variables/10-definition/en/data.yml +++ b/modules/30-variables/10-definition/en/data.yml @@ -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. diff --git a/modules/30-variables/10-definition/es/README.md b/modules/30-variables/10-definition/es/README.md index 195a8f6..085d3e8 100644 --- a/modules/30-variables/10-definition/es/README.md +++ b/modules/30-variables/10-definition/es/README.md @@ -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 +┌──────────┐ ┌──────────┐ +│ greeting │ ──→ │ "Father!"│ +└──────────┘ └──────────┘ ``` -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); + | + 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. + +## 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! +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. diff --git a/modules/30-variables/10-definition/es/data.yml b/modules/30-variables/10-definition/es/data.yml index b48dcfd..2959c3e 100644 --- a/modules/30-variables/10-definition/es/data.yml +++ b/modules/30-variables/10-definition/es/data.yml @@ -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. diff --git a/modules/30-variables/12-change/en/EXERCISE.md b/modules/30-variables/12-change/en/EXERCISE.md index 8c081d6..8a728ab 100644 --- a/modules/30-variables/12-change/en/EXERCISE.md +++ b/modules/30-variables/12-change/en/EXERCISE.md @@ -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 +``` diff --git a/modules/30-variables/12-change/en/README.md b/modules/30-variables/12-change/en/README.md index 0e09b8f..eaba729 100644 --- a/modules/30-variables/12-change/en/README.md +++ b/modules/30-variables/12-change/en/README.md @@ -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. + +## 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. + +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. diff --git a/modules/30-variables/12-change/en/data.yml b/modules/30-variables/12-change/en/data.yml index e98962c..6f3c104 100644 --- a/modules/30-variables/12-change/en/data.yml +++ b/modules/30-variables/12-change/en/data.yml @@ -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. diff --git a/modules/30-variables/12-change/es/README.md b/modules/30-variables/12-change/es/README.md index bc80a9d..20f59b4 100644 --- a/modules/30-variables/12-change/es/README.md +++ b/modules/30-variables/12-change/es/README.md @@ -1,23 +1,50 @@ -La palabra "variable" en sí misma indica que se puede cambiar. Y de hecho, con el tiempo, los valores de las variables pueden cambiar dentro de un programa: +La palabra "variable" en sí misma sugiere que su valor puede cambiar. Esta es una de las principales razones por las que existen las variables. + +Aquí tienes un ejemplo: ```java -var saludo = "¡Padre!"; -System.out.println(saludo); -System.out.println(saludo); -// Ya no se utiliza "var" porque la variable fue definida anteriormente -saludo = "¡Madre!"; -System.out.println(saludo); -System.out.println(saludo); +var greeting = "Father!"; +System.out.println(greeting); // => Father! + +// var ya no se usa, la variable está definida arriba +greeting = "Mother!"; +System.out.println(greeting); // => Mother! ``` -Java es un lenguaje de programación de tipado estático. Esto significa que el tipo de una variable se establece al definirla y no cambia después. +Aquí primero escribimos una cadena (*Father!*) en la variable, y luego otra (*Mother!*). El nombre de la variable no cambió, pero el valor de su interior pasó a ser otro. La palabra clave `var` solo se necesita al crear la variable. Al cambiar el valor, ya no se escribe. + +```text +Antes: greeting ──→ "Father!" +Después: greeting ──→ "Mother!" +``` + +## Para qué cambiar un valor + +En los programas reales, las variables cambian constantemente. Aquí tienes algunas razones: + +- El programa reacciona a las acciones del usuario. Por ejemplo, mientras introduces datos en un formulario de un sitio web, las variables que contienen esos datos cambian constantemente. +- Resultados intermedios. A menudo los datos pasan por una serie de transformaciones, y en cada etapa la variable se actualiza con un nuevo valor. Un mecanismo similar existe incluso en las calculadoras, cuando los valores intermedios se guardan con las teclas `m+` o `m-`. +- Almacenamiento del estado. Si escribes un juego, la posición del personaje, su salud, la puntuación y el nivel actual serán variables que cambian constantemente. -En el ejemplo anterior, asignamos una cadena de texto al crear la variable. El compilador recuerda el tipo y verifica todos los cambios posteriores en la variable. Si intentamos asignar un número a esta misma variable, obtendremos el siguiente error: +## El tipo de la variable no cambia + +Java es un lenguaje de tipado estático. El tipo de una variable se establece al crearla y ya no vuelve a cambiar. En el ejemplo anterior, escribimos una cadena al crear la variable. El compilador recuerda el tipo y verifica todos los cambios posteriores. + +Si intentamos asignar un número a esa misma variable, obtendremos un error: ```java -saludo = 5; -# Error: -# tipos incompatibles: no se puede convertir un entero en java.lang.String +greeting = 5; +// Error: +// incompatible types: int cannot be converted to java.lang.String +// tipos incompatibles: un número no se puede convertir en una cadena ``` -El compilador realiza esta verificación sin ejecutar el código, por eso se llama **tipado estático**. En JavaScript, Ruby, PHP, Python y otros lenguajes dinámicos, este comportamiento no es un error, ya que una variable puede cambiar fácilmente su tipo durante la ejecución. +El compilador realiza esta comprobación sin ejecutar el código. Precisamente por eso a este tipo de tipado se le llama **estático**. En JavaScript, Ruby, PHP, Python y otros lenguajes dinámicos, este comportamiento no se considera un error, y una variable puede cambiar su tipo durante la ejecución. + +## La otra cara de la mutabilidad + +Las variables ofrecen una forma de almacenar datos que cambian a lo largo de la ejecución del programa. Gracias a esto, se pueden escribir programas que se comportan de manera diferente según las condiciones, las acciones del usuario o los resultados de los cálculos. + +Pero la mutabilidad también tiene su otra cara. A veces es difícil entender qué se ha escrito exactamente en una variable en un momento concreto. El desarrollador tiene que rastrear dónde y cómo cambió, sobre todo si el código es largo. + +Esto es justamente lo que se hace durante la depuración. El desarrollador averigua por qué el programa funciona de forma distinta a lo previsto. Se comprueban los valores de las variables, se sigue el orden de ejecución del código y se busca dónde algo salió mal. diff --git a/modules/30-variables/12-change/es/data.yml b/modules/30-variables/12-change/es/data.yml index b03c80c..4f43b95 100644 --- a/modules/30-variables/12-change/es/data.yml +++ b/modules/30-variables/12-change/es/data.yml @@ -1,2 +1,8 @@ --- name: Cambio de variable +tips: [] +definitions: + - name: Variable + description: >- + una forma de guardar información y darle un nombre para su uso posterior en + el código. diff --git a/modules/30-variables/13-variables-naming/en/EXERCISE.md b/modules/30-variables/13-variables-naming/en/EXERCISE.md index 92e86a2..4a79e6f 100644 --- a/modules/30-variables/13-variables-naming/en/EXERCISE.md +++ b/modules/30-variables/13-variables-naming/en/EXERCISE.md @@ -1,4 +1,8 @@ -Create two variables with the names “first number” and “second number” using lowerCamelCase. Write in the first variable the number `1.10`, in the second - `-100`. Display the product of the numbers written in the resulting variables. +Create two variables named "first number" and "second number" in English, using lowerCamelCase. Write the number `1.10` into the first variable, and `-100` into the second. Print the product of the numbers written in the resulting variables to the screen. -The code will work with any names, and our system always checks only the result on the screen, so the execution of this task is under your responsibility. +```text +-110.00000000000001 +``` + +The code will work with any names, and our system always checks only the result on the screen, so completing this task is your responsibility. diff --git a/modules/30-variables/13-variables-naming/en/README.md b/modules/30-variables/13-variables-naming/en/README.md index 1700d73..b909504 100644 --- a/modules/30-variables/13-variables-naming/en/README.md +++ b/modules/30-variables/13-variables-naming/en/README.md @@ -1,12 +1,38 @@ +Imagine we have a program like this: -Variable naming is an important aspect of programming. The names should not only convey the meaning, but also follow the syntactic rules, which, as a rule, are not checked at all at the level of the language, but are necessary during development. The process of writing programs in the modern world is teamwork, and for better teamwork in a team, the code is written in the same style, as if one person was working on it. +```java +var x = "Father!"; +System.out.println(x); +``` -The naming of variables can be divided into three main approaches, which sometimes combine with each other. All these approaches manifest themselves when the variable name consists of several words: +From a technical point of view, everything works. But here a variable named `x` is used. Bad names make code harder to read and understand. Here are a few examples of unfortunate variables: -* kebab-case - the variable components are separated by a hyphen. For example: `my-super-var`. -* snake_case - underscore is used for separation. For example: `my_super_var`. -* CamelCase - each word in a variable is written with a capital letter. For example: `MySuperVar`. +```java +var a = "John"; +var n = 42; +var ddr = "New York"; +``` -In Java, CamelCase and its variation lowerCamelCase are used, in which the first letter of the first word is lowercase. It is lowerCamelCase that is used for variables. +What are these variables? What is stored in them? To understand that, you have to read all the rest of the code and guess from the context. -Another common rule is: do not use transliteration for names, only English. If you experience difficulties with English, use a translator. Over time, digging into someone else's code, you will form the right concepts for naming. +The computer does not care what a variable is called. To it, `x`, `abc`, `message`, or `elephantInTheRoom` are just labels for storing data. For people, something else matters. Programmers read code much more often than they write it, and not only their own code, but also code written by other people. That is why variable names become an important part of communication through code. + +## Good examples + +```java +var userName = "Arya Stark"; +var unpaidOrdersCount = 3; +var maxAttempts = 5; +``` + +A good variable name helps you understand what the program does without having to read closely into every line. It is especially important to give names whose meaning is clear without context, without reading all the surrounding code. + +Here are a few tips: + +- Use English. It is the international standard. It is better to write `ordersCount` instead of `kolvoZakazov`. If English is still difficult for you, use a translator, that is fine. Over time it will become easier. +- Try to make the name reflect the meaning of the variable. Let it be a bit longer, but understandable. +- Do not be afraid to spend time picking a good name. It is an investment in the readability and maintainability of the code. + +Among programmers there is even a joke: "Some of the hardest tasks in programming remain cache invalidation and coming up with names for variables". Sometimes it really is hard to come up with a suitable name. Here is an example: how would you name a variable that stores the number of unpaid orders from customers with debt from the previous quarter? + +And now a little exercise. Come up with a name for a variable that will store "the number of the king's brothers and sisters". Write it down in a notebook or send it to yourself by email. Just the name, without explanations. After some time, look at it again and check whether the meaning of the variable is clear from the name alone. diff --git a/modules/30-variables/13-variables-naming/en/data.yml b/modules/30-variables/13-variables-naming/en/data.yml index 7b43fc1..99a15e7 100644 --- a/modules/30-variables/13-variables-naming/en/data.yml +++ b/modules/30-variables/13-variables-naming/en/data.yml @@ -1,2 +1,13 @@ --- -name: Variable naming +name: Choosing a variable name +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) + - > + [Errors in variable + naming](https://ru.hexlet.io/blog/posts/naming-errors-1?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. diff --git a/modules/30-variables/13-variables-naming/es/EXERCISE.md b/modules/30-variables/13-variables-naming/es/EXERCISE.md index 0e44fa6..8730fd0 100644 --- a/modules/30-variables/13-variables-naming/es/EXERCISE.md +++ b/modules/30-variables/13-variables-naming/es/EXERCISE.md @@ -1,8 +1,8 @@ -Crea dos variables con los nombres "primerNumero" y "segundoNumero" en inglés, utilizando lowerCamelCase. Asigna el número `1.10` a la primera variable y `-100` a la segunda. Imprime en pantalla el producto de los números almacenados en las variables resultantes. +Crea dos variables con los nombres «primer número» y «segundo número» en inglés, utilizando lowerCamelCase. Escribe el número `1.10` en la primera variable y `-100` en la segunda. Imprime en pantalla el producto de los números almacenados en las variables resultantes. ```text -110.00000000000001 ``` -El código funcionará con cualquier nombre, y nuestro sistema siempre verifica solo el resultado en pantalla, por lo que completar esta tarea es responsabilidad tuya. +El código funcionará con cualquier nombre, y nuestro sistema siempre verifica solo el resultado en pantalla, por lo que completar esta tarea es tu responsabilidad. diff --git a/modules/30-variables/13-variables-naming/es/README.md b/modules/30-variables/13-variables-naming/es/README.md index 522f565..b143231 100644 --- a/modules/30-variables/13-variables-naming/es/README.md +++ b/modules/30-variables/13-variables-naming/es/README.md @@ -1,15 +1,38 @@ -Imaginemos que el programa del último curso se ve así: +Imagina que tenemos un programa como este: ```java -var x = "¡Padre!"; -System.out.println(x); +var x = "Father!"; System.out.println(x); ``` -Todavía funciona, pero el nombre de la variable ha cambiado a `x`. A la computadora no le importa cómo llamamos a las variables. Los nombres son importantes para los programadores, ya que leemos código con mucha más frecuencia de lo que escribimos. Y no solo nuestro propio código, sino también el código escrito por otras personas. La mitad del éxito en el análisis de código depende de la calidad y claridad de los nombres de las variables. +Desde el punto de vista técnico, todo funciona. Pero aquí se usa una variable llamada `x`. Los nombres malos dificultan leer y entender el código. Aquí tienes algunos ejemplos de variables poco afortunadas: + +```java +var a = "John"; +var n = 42; +var ddr = "New York"; +``` + +¿Qué son estas variables? ¿Qué se guarda en ellas? Para entenderlo, hay que leer todo el resto del código y adivinar por el contexto. + +A la computadora le da igual cómo se llame una variable. Para ella, `x`, `abc`, `message` o `elephantInTheRoom` son simplemente etiquetas para almacenar datos. Para las personas es distinto. Los programadores leen código mucho más a menudo de lo que lo escriben, y no solo el suyo propio, sino también el escrito por otras personas. Por eso los nombres de las variables se convierten en una parte importante de la comunicación a través del código. + +## Buenos ejemplos + +```java +var userName = "Arya Stark"; +var unpaidOrdersCount = 3; +var maxAttempts = 5; +``` + +Un buen nombre de variable ayuda a entender qué hace el programa sin necesidad de leer con atención cada línea. Es especialmente importante dar nombres cuyo significado se entienda sin contexto, sin leer todo el código de alrededor. + +Aquí tienes algunos consejos: -Es mejor tomarse el tiempo para pensar en un nombre que describa la esencia de la variable, en lugar de nombrarla al azar y tener que cambiarla en el futuro. Intente darles nombres que sean comprensibles sin contexto, sin tener que estudiar el código circundante. +- Usa el inglés. Es el estándar internacional. Es mejor escribir `ordersCount` en lugar de `kolvoZakazov`. Si el inglés todavía te resulta difícil, usa un traductor, es algo normal. Con el tiempo se hará más fácil. +- Procura que el nombre refleje el significado de la variable. Que sea un poco más largo, pero comprensible. +- No tengas miedo de dedicar tiempo a elegir un buen nombre. Es una inversión en la legibilidad y el mantenimiento del código. -Existe una regla general aceptada: no utilice transliteraciones para los nombres, solo use el idioma inglés. Si tiene dificultades con el inglés, utilice un traductor. Con el tiempo, al investigar el código de otras personas, formará conceptos adecuados para la nomenclatura. +Entre los programadores incluso hay un chiste: "Algunas de las tareas más difíciles en programación siguen siendo la invalidación de la caché y la elección de nombres para las variables". A veces inventar un nombre adecuado es realmente difícil. Aquí tienes un ejemplo: ¿cómo llamarías a una variable que almacena la cantidad de pedidos impagos de clientes con deuda del trimestre anterior? -Entre los desarrolladores hay un chiste: "lo más difícil de la programación son los nombres de las variables y la invalidación de la caché". De hecho, es difícil inventar nombres. ¿Cómo llamaría a una variable que almacena "la cantidad de pedidos impagos de clientes con deudas del trimestre anterior"? +Y ahora un pequeño ejercicio. Inventa un nombre para una variable que vaya a almacenar "la cantidad de hermanos y hermanas del rey". Anótalo en una libreta o envíatelo por correo. Solo el nombre, sin explicaciones. Al cabo de un tiempo, míralo de nuevo y comprueba si el significado de la variable se entiende solo por el nombre. diff --git a/modules/30-variables/13-variables-naming/es/data.yml b/modules/30-variables/13-variables-naming/es/data.yml index dc7f1e0..b72beea 100644 --- a/modules/30-variables/13-variables-naming/es/data.yml +++ b/modules/30-variables/13-variables-naming/es/data.yml @@ -1,2 +1,11 @@ --- -name: Selección de nombres de variables +name: Elección del nombre de una variable +tips: + - > + [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. diff --git a/modules/30-variables/15-variable-expressions/en/EXERCISE.md b/modules/30-variables/15-variable-expressions/en/EXERCISE.md index 35e1cda..5d4c37b 100644 --- a/modules/30-variables/15-variable-expressions/en/EXERCISE.md +++ b/modules/30-variables/15-variable-expressions/en/EXERCISE.md @@ -1,13 +1,14 @@ -Write a program that takes the original amount of euros recorded in the variable `eurosCount`, converts the euro into dollars and displays on the screen. Then, the resulting value translates into rubles and displays on the new line. +Write a program that takes the initial amount of euros written in the variable `eurosCount`, converts euros to dollars, and prints the result to the screen. Then it converts the resulting value to rubles and prints it on a new line. -Example withdrawal for 100 euros: +Example output for 100 euros: ```text 125.0 7500.0 ``` -We believe that: +We assume that: + - 1 euro = 1.25 dollars - 1 dollar = 60 rubles diff --git a/modules/30-variables/15-variable-expressions/en/README.md b/modules/30-variables/15-variable-expressions/en/README.md index c708cd6..c252ad4 100644 --- a/modules/30-variables/15-variable-expressions/en/README.md +++ b/modules/30-variables/15-variable-expressions/en/README.md @@ -1,53 +1,55 @@ +Variables are useful not only for storing and reusing information, but also for simplifying complex calculations. -Variables are useful not only for storing and reusing information, but also for simplifying complex calculations. Let's look at an example: you need to convert euros to rubles in dollars. Such conversions through an intermediate currency are often made by banks when shopping abroad. +Let's look at an example: you need to convert euros to rubles through dollars. Banks often make such conversions through an intermediate currency when you shop abroad. -To begin with we will transfer 50 euros to dollars. Suppose that one euro — 1.25 dollars: +To begin with, let's convert 50 euros to dollars. Suppose that one euro is 1.25 dollars: ```java var dollarsCount = 50 * 1.25; -System.out.print(dollarsCount); +System.out.println(dollarsCount); ``` -In the previous lesson we wrote down a specific value in a variable. And here `var dollarsCount = 50 * 1.25;` to the right of the sign equals **expression**. The program will calculate the result — `62.5` — and write it into a variable. From the point of view of the program, it does not matter what is in front of him: `62.5` or `50 * 1.25`, both of these options are expressions that need to be calculated. And they are calculated in the same value — `62.5`. - -Any string is an expression. String concatenation is also an expression. When the program sees the expression, it processes it and generates the result — **the value of the expression**. Here are some examples of expressions, and in the comments to the right of each expression is the total value: +In the previous block, we wrote a specific value into a variable. But here, to the right of the equals sign, there is an **expression**: ```java -62.5 // => 62.5 -50 * 1.25 // => 62.5 -120 / 10 * 2 // => 24 -Integer.parseInt("100") // => 100 - -"hello" // => "hello" -"Good" + "will" // => "Goodwill" +var dollarsCount = 50 * 1.25; ``` -The rules for constructing code (language grammar) are such that in those places where an expression is expected, you can put any calculation (not only mathematical, but also, for example, string — as concatenation), and the program will remain operable. For this reason, it is impossible to describe and show all use cases of all operations. +The program will calculate the result *62.5* and write it into the variable. From the program's point of view, it does not matter what is written: *62.5* or *50 * 1.25*. Both options are expressions that need to be calculated. And they are calculated to the same value *62.5*. -Programs consist of many combinations of expressions, and understanding this concept is one of the key steps in your path. +Any string is an expression. String concatenation is also an expression. When the program sees an expression, it calculates it and **returns** the result. -Let's return to our monetary program. We write the value of the dollar in rubles, as a separate variable. We calculate the price of 50 euros in dollars, multiplying them by `1.25`. Suppose that 1 dollar — 60 rubles: +Here are a few examples of expressions. In the comments to the right of each expression, the resulting value is written: ```java -var rublesPerDollar = 60; -var dollarsCount = 50 * 1.25; // => 62.5 -var rublesCount = dollarsCount * rublesPerDollar; // => 3750 - -System.out.print(rublesCount); +62.5 // 62.5 +50 * 1.25 // 62.5 +120 / 10 * 2 // 24 +"Hexlet" // "Hexlet" +"Good" + "will" // "Goodwill" ``` -Now let's add text to the output using concatenation: +The rules for building code are such that in the places where an expression is expected, you can put any calculation. Moreover, the calculation can be not only mathematical, but also a string one — for example, concatenation. And the program will still remain working. + +For this reason, it is impossible to describe and show all the cases of using all operations. Programs consist of many combinations of expressions, and understanding this concept is one of the key steps on your path. + +Let's return to our currency program. Let's write the value of the dollar in rubles as a separate variable. Let's calculate the price of 50 euros in dollars by multiplying them by 1.25. Suppose that 1 dollar is 60 rubles: ```java var rublesPerDollar = 60; -var dollarsCount = 50 * 1.25; // => 62.5 -var rublesCount = dollarsCount * rublesPerDollar; // => 3750 - -System.out.print("The price is" + rublesCount + "rubles"); +var dollarsCount = 50 * 1.25; // 62.5 +var rublesCount = dollarsCount * rublesPerDollar; // 3750 +System.out.println(rublesCount); // => 3750 ``` -The price is 3750 rubles +And now let's add text to the output using concatenation: -Any variable can be part of any expression. At the time of calculation, the value of the variable is substituted for its value. +```java +var rublesPerDollar = 60; +var dollarsCount = 50 * 1.25; // 62.5 +var rublesCount = dollarsCount * rublesPerDollar; // 3750 +System.out.println("The price is " + rublesCount + " rubles"); +// => The price is 3750 rubles +``` -The value of `dollarsCount` is calculated before it is used in other expressions. When the time comes to use a variable, Java "knows" the value, because it has already calculated it. +Any variable can be part of any expression. At the moment of calculation, the value of the variable is substituted for its name. The value of `dollarsCount` is calculated before it starts being used in other expressions. When the moment to use the variable comes, Java knows the value, because it has already calculated it. diff --git a/modules/30-variables/15-variable-expressions/en/data.yml b/modules/30-variables/15-variable-expressions/en/data.yml index 99509a2..cee3067 100644 --- a/modules/30-variables/15-variable-expressions/en/data.yml +++ b/modules/30-variables/15-variable-expressions/en/data.yml @@ -2,5 +2,9 @@ name: Expressions in definitions tips: - > - To translate a line, you can use `\ n` between the withdrawal of dollars and - rubles. + To move to a new line, you can use `\n` between printing dollars and rubles, + or call the `println()` method as many times as needed. +definitions: + - name: Variable + description: >- + a way to store information and give it a name for later use in the code. diff --git a/modules/30-variables/15-variable-expressions/es/EXERCISE.md b/modules/30-variables/15-variable-expressions/es/EXERCISE.md index 23703f2..1bd7d96 100644 --- a/modules/30-variables/15-variable-expressions/es/EXERCISE.md +++ b/modules/30-variables/15-variable-expressions/es/EXERCISE.md @@ -1,5 +1,5 @@ -Escribe un programa que tome la cantidad inicial de euros almacenada en la variable `amountEuros`, convierta los euros a dólares y los muestre en la pantalla. Luego, convierte el valor obtenido a rublos y lo muestra en una nueva línea. +Escribe un programa que tome la cantidad inicial de euros almacenada en la variable `eurosCount`, convierta los euros a dólares y lo muestre en pantalla. Luego convierte el valor obtenido a rublos y lo muestra en una nueva línea. Ejemplo de salida para 100 euros: @@ -8,7 +8,7 @@ Ejemplo de salida para 100 euros: 7500.0 ``` -Supongamos que: +Suponemos que: - 1 euro = 1.25 dólares - 1 dólar = 60 rublos diff --git a/modules/30-variables/15-variable-expressions/es/README.md b/modules/30-variables/15-variable-expressions/es/README.md index 72e7182..6057fe4 100644 --- a/modules/30-variables/15-variable-expressions/es/README.md +++ b/modules/30-variables/15-variable-expressions/es/README.md @@ -1,25 +1,25 @@ Las variables son útiles no solo para almacenar y reutilizar información, sino también para simplificar cálculos complejos. -Veamos un ejemplo: necesitamos convertir euros a rublos a través de dólares. Los bancos a menudo realizan conversiones similares a través de una moneda intermedia al realizar compras en el extranjero. +Veamos un ejemplo: necesitamos convertir euros a rublos a través de dólares. Los bancos suelen hacer conversiones similares a través de una moneda intermedia al realizar compras en el extranjero. -Primero, convirtamos 50 euros a dólares. Supongamos que un euro equivale a 1.25 dólares: +Para empezar, convirtamos 50 euros a dólares. Supongamos que un euro son 1.25 dólares: ```java -var amountDollars = 50 * 1.25; -System.out.println(amountDollars); +var dollarsCount = 50 * 1.25; +System.out.println(dollarsCount); ``` -En el bloque anterior, asignamos un valor específico a una variable. Pero aquí, a la derecha del signo igual, hay una **expresión**: +En el bloque anterior escribíamos un valor concreto en la variable. Pero aquí, a la derecha del signo igual, hay una **expresión**: ```java -var amountDollars = 50 * 1.25; +var dollarsCount = 50 * 1.25; ``` -El programa calculará el resultado *62.5* y lo asignará a la variable. Desde el punto de vista del programa, no importa si está escrito *62.5* o *50 * 1.25*. Ambas opciones son expresiones que deben evaluarse. Y se evalúan en el mismo valor *62.5*. +El programa calculará el resultado *62.5* y lo escribirá en la variable. Desde el punto de vista del programa, no importa qué esté escrito: *62.5* o *50 * 1.25*. Ambas variantes son expresiones que hay que calcular. Y ambas se calculan al mismo valor *62.5*. -Cualquier cadena de texto es una expresión. La concatenación de cadenas también es una expresión. Cuando el programa encuentra una expresión, la evalúa y **devuelve** el resultado. +Cualquier cadena es una expresión. La concatenación de cadenas también es una expresión. Cuando el programa ve una expresión, la calcula y **devuelve** el resultado. -Aquí tienes algunos ejemplos de expresiones. A la derecha de cada expresión, se muestra el valor resultante: +Aquí tienes algunos ejemplos de expresiones. En los comentarios a la derecha de cada expresión se indica el valor resultante: ```java 62.5 // 62.5 @@ -29,27 +29,27 @@ Aquí tienes algunos ejemplos de expresiones. A la derecha de cada expresión, s "Good" + "will" // "Goodwill" ``` -Las reglas de construcción del código permiten colocar cualquier cálculo donde se espera una expresión. Y el cálculo puede ser tanto matemático como de cadenas de texto, como la concatenación. El programa seguirá funcionando correctamente. +Las reglas de construcción del código son tales que, en los lugares donde se espera una expresión, se puede poner cualquier cálculo. Además, el cálculo puede ser no solo matemático, sino también de cadenas, por ejemplo, la concatenación. Y el programa seguirá funcionando. -Por esta razón, no es posible describir y mostrar todos los casos de uso de todas las operaciones. Los programas están compuestos por muchas combinaciones de expresiones, y comprender este concepto es uno de los pasos clave en tu camino. +Por esta razón, es imposible describir y mostrar todos los casos de uso de todas las operaciones. Los programas están formados por muchas combinaciones de expresiones, y comprender este concepto es uno de los pasos clave en tu camino. -Volvamos a nuestro programa de conversión de moneda. Guardemos el valor del dólar en rublos como una variable separada. Calculemos el precio de 50 euros en dólares multiplicándolos por 1.25. Supongamos que 1 dólar equivale a 60 rublos: +Volvamos a nuestro programa de divisas. Escribamos el valor del dólar en rublos como una variable aparte. Calculemos el precio de 50 euros en dólares multiplicándolos por 1.25. Supongamos que 1 dólar son 60 rublos: ```java var rublesPerDollar = 60; -var amountDollars = 50 * 1.25; // 62.5 -var amountRubles = amountDollars * rublesPerDollar; // 3750 -System.out.println(amountRubles); // => 3750 +var dollarsCount = 50 * 1.25; // 62.5 +var rublesCount = dollarsCount * rublesPerDollar; // 3750 +System.out.println(rublesCount); // => 3750 ``` -Y ahora agreguemos texto a la salida utilizando la concatenación: +Y ahora agreguemos texto a la salida mediante la concatenación: ```java var rublesPerDollar = 60; -var amountDollars = 50 * 1.25; // 62.5 -var amountRubles = amountDollars * rublesPerDollar; // 3750 -System.out.println("El precio es " + amountRubles + " rublos"); -// => El precio es 3750 rublos +var dollarsCount = 50 * 1.25; // 62.5 +var rublesCount = dollarsCount * rublesPerDollar; // 3750 +System.out.println("The price is " + rublesCount + " rubles"); +// => The price is 3750 rubles ``` -Cualquier variable puede formar parte de cualquier expresión. En el momento de la evaluación, el valor de la variable se sustituye en lugar de su nombre. El valor de `amountDollars` se calcula antes de que se utilice en otras expresiones. Cuando llega el momento de usar la variable, Java conoce su valor porque ya lo ha calculado. +Cualquier variable puede formar parte de cualquier expresión. En el momento del cálculo, el nombre de la variable se sustituye por su valor. El valor de `dollarsCount` se calcula antes de que empiece a usarse en otras expresiones. Cuando llega el momento de usar la variable, Java conoce su valor, porque ya lo ha calculado. diff --git a/modules/30-variables/15-variable-expressions/es/data.yml b/modules/30-variables/15-variable-expressions/es/data.yml index bbe0868..b28fc53 100644 --- a/modules/30-variables/15-variable-expressions/es/data.yml +++ b/modules/30-variables/15-variable-expressions/es/data.yml @@ -2,6 +2,11 @@ name: Expresiones en definiciones tips: - > - Para imprimir una nueva línea, puedes usar `\n` entre la impresión de los - dólares y los rublos, o puedes usar el método `println()` la cantidad de - veces necesaria. + Para pasar a una nueva línea, puedes usar `\n` entre la impresión de los + dólares y los rublos, o usar el método `println()` tantas veces como sea + necesario. +definitions: + - name: Variable + description: >- + una forma de guardar información y darle un nombre para su uso posterior en + el código. diff --git a/modules/30-variables/18-variables-concatenation/en/EXERCISE.md b/modules/30-variables/18-variables-concatenation/en/EXERCISE.md index 0d6953a..c443ffd 100644 --- a/modules/30-variables/18-variables-concatenation/en/EXERCISE.md +++ b/modules/30-variables/18-variables-concatenation/en/EXERCISE.md @@ -1,18 +1,18 @@ -Sites are constantly sending emails to their users. A typical task is to make an automatic sending of a personal letter, where the user name is in the header. If somewhere in the site base the name of the person is stored as a string, then the task of generating the header is reduced to concatenation: for example, you need to glue the string `Hello` with the string where the name is written. +Websites constantly send emails to their users. A typical task is to set up automatic sending of a personal email where the header contains the user's name. If a person's name is stored somewhere in the site's database as a string, then the task of generating the header comes down to concatenation: for example, you need to join the string *Hello* with the string that holds the name. -Write a program that will generate the header and body of the letter, using the ready-made variables, and display the resulting lines on the screen. +Write a program that will generate the header and body of the email using the ready-made variables, and print the resulting strings to the screen. -For the title, use the variables `firstName` and `greeting`, a comma and an exclamation point. Display it in the correct order. +For the header, use the variables `firstName` and `greeting`, a comma, and an exclamation mark. Print it to the screen in the correct order. -For the body of the letter, use the variables `info` and `intro`, with the second sentence should be on a new line. +For the body of the email, use the variables `info` and `intro`, and the second sentence must be on a new line. The result on the screen will look like this: ```text Hello, Joffrey! -Here is an important information about your account security. +Here is important information about your account security. We couldn't verify you mother's maiden name. ``` -Perform the job using only two `System.out.print`. +Complete the task using only two `System.out.println()`. diff --git a/modules/30-variables/18-variables-concatenation/en/README.md b/modules/30-variables/18-variables-concatenation/en/README.md index 0b34320..d237929 100644 --- a/modules/30-variables/18-variables-concatenation/en/README.md +++ b/modules/30-variables/18-variables-concatenation/en/README.md @@ -1,29 +1,83 @@ +Strings can be joined directly using concatenation. Now let's do the same, but with variables. The syntax stays the same, the program substitutes the values of the variables. -To consolidate the previous topic, try using variables with concatenation. Syntactically nothing changes: we can concatenate (glue) two lines: +## Joining two strings directly ```java - var what = "Kings" + "road"; -System.out.print(what); // => "Kingsroad" +System.out.println(what); // => Kingsroad ``` -... which means we can concatenate a string and one variable in which the string is written: +Here two strings are joined into one. This is how concatenation works: the `+` operator adds strings together and creates a new string. -```java +## Joining a string and a variable +If the variable `first` holds the string `"Kings"`, we can join it with another string: + +```java var first = "Kings"; var what = first + "road"; - -System.out.print(what); // => "Kingsroad" +System.out.println(what); // => Kingsroad ``` -... and even concatenate two variables in which the lines are written: +Java will substitute the value of the variable, perform the operation, and create the resulting string. + +## Joining two variables + +In exactly the same way, you can combine the values of two variables if both contain strings: ```java +var first = "Kings"; +var last = "road"; +var what = first + last; +System.out.println(what); // => Kingsroad +``` + +You can also add spaces: +```java var first = "Kings"; var last = "road"; +var full = first + " " + last; +System.out.println(full); // => Kings road +``` -var what = first + last; -System.out.print(what); // => "Kingsroad" +```text +first = "Kings" +last = "road" + +first + " " + last +└─┬──┘ └─┬─┘ +"Kings" + " " + "road" +└────────┬─────────┘ + "Kings road" ``` + +## What if a variable contains a number + +In Java, the `+` operator can join a string with a number. If at least one operand is a string, the number is automatically turned into a string, and you get a single string: + +```java +var age = 42; +System.out.println("Age: " + age); // => Age: 42 +``` + +Java sees the string `"Age: "` on the left, so it converts the number `42` into the string `"42"` and joins them together. The same works with the results of calculations: + +```java +var price = 50 * 1.25 * 6.91; // => 431.875 +System.out.println("Price in yuans: " + price); +// => Price in yuans: 431.875 +``` + +Here Java first calculates the expression, gets the number `431.875`, then turns it into a string and glues it to the text on the left. + +## The order of calculation matters + +When numbers and strings meet in the same expression, the result depends on the order of operations. From left to right, `+` first adds two numbers, and only then glues them to the string: + +```java +System.out.println("Sum: " + 2 + 3); // => Sum: 23 +System.out.println("Sum: " + (2 + 3)); // => Sum: 5 +``` + +In the first line, `"Sum: " + 2` is already turned into the string `"Sum: 2"`, and then `3` is glued to it, resulting in `"Sum: 23"`. In the second line, the parentheses force `2 + 3` to be added first, giving the number `5`, and only then it is joined with the string. diff --git a/modules/30-variables/18-variables-concatenation/en/data.yml b/modules/30-variables/18-variables-concatenation/en/data.yml index 16d1485..866972b 100644 --- a/modules/30-variables/18-variables-concatenation/en/data.yml +++ b/modules/30-variables/18-variables-concatenation/en/data.yml @@ -1,10 +1,15 @@ --- -name: Variables and Concatenation +name: Variables and concatenation tips: - > - Consider with which line and in what order you need to glue the - modules.variables together in order to get such a two-line output of the - letter body. + Think about which string and in what order you need to concatenate the + variables to get such a two-line output of the email body. - > Remember that you can create a string that contains only the control - sequence `\n`. + sequence `\n`. You can concatenate this string with the variables to format + the text correctly. +definitions: + - name: Concatenation + description: > + the operation of joining two strings. For example, `System.out.println("King's " + + "Landing")` diff --git a/modules/30-variables/18-variables-concatenation/es/EXERCISE.md b/modules/30-variables/18-variables-concatenation/es/EXERCISE.md index 6cb389d..93b568b 100644 --- a/modules/30-variables/18-variables-concatenation/es/EXERCISE.md +++ b/modules/30-variables/18-variables-concatenation/es/EXERCISE.md @@ -1,13 +1,13 @@ -Los sitios web constantemente envían correos electrónicos a sus usuarios. Una tarea típica es enviar automáticamente un correo electrónico personalizado, donde el nombre de usuario estará en el asunto. Si el nombre del usuario se almacena en algún lugar de la base de datos del sitio web como una cadena, la tarea de generar el asunto se reduce a la concatenación: por ejemplo, debes concatenar la cadena Hola con la cadena que contiene el nombre. +Los sitios web envían correos electrónicos constantemente a sus usuarios. Una tarea típica es configurar el envío automático de un correo personalizado, donde el encabezado contenga el nombre del usuario. Si el nombre de una persona se guarda en algún lugar de la base de datos del sitio como una cadena, la tarea de generar el encabezado se reduce a la concatenación: por ejemplo, hay que unir la cadena *Hola* con la cadena que contiene el nombre. -Escribe un programa que genere el asunto y el cuerpo del correo electrónico, utilizando las variables ya definidas, y muestre las cadenas resultantes en la pantalla. +Escribe un programa que genere el encabezado y el cuerpo del correo utilizando las variables ya preparadas, y que muestre las cadenas resultantes en la pantalla. -Para el asunto, utiliza las variables nombre y saludo, una coma y un signo de exclamación. Muestra esto en el orden correcto. +Para el encabezado, usa las variables `firstName` y `greeting`, una coma y un signo de exclamación. Muéstralo en la pantalla en el orden correcto. -Para el cuerpo del correo electrónico, utiliza las variables informacion e introduccion, con la segunda oración en una nueva línea. +Para el cuerpo del correo, usa las variables `info` e `intro`, y la segunda oración debe estar en una nueva línea. -El resultado en la pantalla debería lucir así: +El resultado en la pantalla se verá así: ```text Hello, Joffrey! @@ -15,4 +15,4 @@ Here is important information about your account security. We couldn't verify you mother's maiden name. ``` -Completa la tarea utilizando solamente dos System.out.println(). +Completa la tarea utilizando solo dos `System.out.println()`. diff --git a/modules/30-variables/18-variables-concatenation/es/README.md b/modules/30-variables/18-variables-concatenation/es/README.md index 4e81f17..2b79a5b 100644 --- a/modules/30-variables/18-variables-concatenation/es/README.md +++ b/modules/30-variables/18-variables-concatenation/es/README.md @@ -1,23 +1,83 @@ -Las variables y la concatenación se pueden combinar. Sintácticamente nada cambia, porque sabemos cómo concatenar, es decir, unir dos cadenas: +Las cadenas se pueden unir directamente mediante la concatenación. Ahora hagamos lo mismo, pero con variables. La sintaxis sigue siendo la misma, el programa sustituye los valores de las variables. + +## Unimos dos cadenas directamente + +```java +var what = "Kings" + "road"; +System.out.println(what); // => Kingsroad +``` + +Aquí dos cadenas se unen en una sola. Así funciona la concatenación: el operador `+` suma las cadenas y crea una nueva cadena. + +## Unimos una cadena y una variable + +Si en la variable `first` está la cadena `"Kings"`, podemos unirla con otra cadena: + +```java +var first = "Kings"; +var what = first + "road"; +System.out.println(what); // => Kingsroad +``` + +Java sustituirá el valor de la variable, ejecutará la operación y creará la cadena resultante. + +## Unimos dos variables + +Del mismo modo, se pueden combinar los valores de dos variables si ambas contienen cadenas: + +```java +var first = "Kings"; +var last = "road"; +var what = first + last; +System.out.println(what); // => Kingsroad +``` + +También se pueden añadir espacios: + +```java +var first = "Kings"; +var last = "road"; +var full = first + " " + last; +System.out.println(full); // => Kings road +``` + +```text +first = "Kings" +last = "road" + +first + " " + last +└─┬──┘ └─┬─┘ +"Kings" + " " + "road" +└────────┬─────────┘ + "Kings road" +``` + +## Y si una variable contiene un número + +En Java, el operador `+` sabe unir una cadena con un número. Si al menos uno de los operandos es una cadena, el número se convierte automáticamente en cadena, y se obtiene una cadena común: ```java -var que = "Camino" + "de Reyes"; -System.out.println(que); // => CaminodeReyes +var age = 42; +System.out.println("Age: " + age); // => Age: 42 ``` -Esto significa que podemos concatenar una cadena y una variable que contiene una cadena: +Java ve la cadena `"Age: "` a la izquierda, por eso convierte el número `42` en la cadena `"42"` y las une. Lo mismo funciona con los resultados de los cálculos: ```java -var primero = "Caminos"; -var que = primero + "de Reyes"; -System.out.println(que); // => CaminodeReyes +var price = 50 * 1.25 * 6.91; // => 431.875 +System.out.println("Price in yuans: " + price); +// => Price in yuans: 431.875 ``` -Incluso podemos concatenar dos variables que contienen cadenas: +Aquí Java primero calcula la expresión, obtiene el número `431.875`, luego lo convierte en cadena y lo pega al texto de la izquierda. + +## El orden de cálculo importa + +Cuando en una misma expresión aparecen números y cadenas, el resultado depende del orden de las operaciones. De izquierda a derecha, `+` primero suma dos números y solo después los pega a la cadena: ```java -var primero = "Caminos"; -var ultimo = "de Reyes"; -var que = primero + ultimo; -System.out.println(que); // => CaminodeReyes +System.out.println("Sum: " + 2 + 3); // => Sum: 23 +System.out.println("Sum: " + (2 + 3)); // => Sum: 5 ``` + +En la primera línea, `"Sum: " + 2` ya se convierte en la cadena `"Sum: 2"`, y luego se le pega `3`, y se obtiene `"Sum: 23"`. En la segunda línea, los paréntesis obligan a sumar primero `2 + 3`, obtener el número `5`, y solo después unirlo con la cadena. diff --git a/modules/30-variables/18-variables-concatenation/es/data.yml b/modules/30-variables/18-variables-concatenation/es/data.yml index 3155979..4363cd8 100644 --- a/modules/30-variables/18-variables-concatenation/es/data.yml +++ b/modules/30-variables/18-variables-concatenation/es/data.yml @@ -1,9 +1,15 @@ --- -name: Variables y Concatenación +name: Variables y concatenación tips: - > Piensa en qué cadena y en qué orden debes concatenar las variables para - obtener una salida de dos líneas para el cuerpo del correo electrónico. + obtener esa salida de dos líneas del cuerpo del correo. - > Recuerda que puedes crear una cadena que contenga solo la secuencia de - control '\n'. + control `\n`. Puedes concatenar esta cadena con las variables para formatear + el texto correctamente. +definitions: + - name: Concatenación + description: > + la operación de unir dos cadenas. Por ejemplo, `System.out.println("King's " + + "Landing")` diff --git a/modules/30-variables/19-naming-style/en/EXERCISE.md b/modules/30-variables/19-naming-style/en/EXERCISE.md index 0d6953a..37ccb46 100644 --- a/modules/30-variables/19-naming-style/en/EXERCISE.md +++ b/modules/30-variables/19-naming-style/en/EXERCISE.md @@ -1,18 +1,8 @@ -Sites are constantly sending emails to their users. A typical task is to make an automatic sending of a personal letter, where the user name is in the header. If somewhere in the site base the name of the person is stored as a string, then the task of generating the header is reduced to concatenation: for example, you need to glue the string `Hello` with the string where the name is written. - -Write a program that will generate the header and body of the letter, using the ready-made variables, and display the resulting lines on the screen. - -For the title, use the variables `firstName` and `greeting`, a comma and an exclamation point. Display it in the correct order. - -For the body of the letter, use the variables `info` and `intro`, with the second sentence should be on a new line. - -The result on the screen will look like this: +Create two variables named "first number" and "second number" in English, using lowerCamelCase. Write the number `11` into the first variable, and `-100` into the second. Print the product of the numbers written in the resulting variables to the screen. ```text -Hello, Joffrey! -Here is an important information about your account security. -We couldn't verify you mother's maiden name. +-1100 ``` -Perform the job using only two `System.out.print`. +The code will work with any names, and our system always checks only the result on the screen, so completing this task is your responsibility. diff --git a/modules/30-variables/19-naming-style/en/README.md b/modules/30-variables/19-naming-style/en/README.md index 0b34320..0ad5197 100644 --- a/modules/30-variables/19-naming-style/en/README.md +++ b/modules/30-variables/19-naming-style/en/README.md @@ -1,29 +1,52 @@ +`greeting` serves as an example of a simple and clear variable name. But names like `name`, `email`, or `price` are often not enough. For example, you need to describe a user's name, the total number of orders, the maximum length of a message. Such names already consist of several words. What will a variable name look like in that case? -To consolidate the previous topic, try using variables with concatenation. Syntactically nothing changes: we can concatenate (glue) two lines: +Different programming languages use different naming styles. This determines what a compound name looks like. For example, here is how you can write a variable that stores the maximum length of a message: -```java +1. `maxmessagelength` +1. `maxMessageLength` +1. `max-message-length` +1. `max_message_length` -var what = "Kings" + "road"; -System.out.print(what); // => "Kingsroad" -``` +## Main styles -... which means we can concatenate a string and one variable in which the string is written: +In variable naming, four main approaches can be distinguished. All of them show up when a name consists of several words: -```java +- kebab-case: words are separated by a hyphen, for example `max-message-length`. -var first = "Kings"; -var what = first + "road"; + Does not work in Java, because the hyphen is treated as the subtraction operator. -System.out.print(what); // => "Kingsroad" -``` +- snake_case: words are separated by an underscore, for example `max_message_length`. + +- CamelCase (or UpperCamelCase): each word starts with a capital letter without separators, for example `MaxMessageLength`. + +- lowerCamelCase: the same, but the first word starts with a lowercase letter, for example `maxMessageLength`. + +## How to do it correctly in Java -... and even concatenate two variables in which the lines are written: +For variable names in Java, the lowerCamelCase style is adopted. Words are joined together, and each word except the first is written with a capital letter: ```java +var userName = "Daenerys"; +var maxLength = 280; +var totalOrdersCount = 17; +``` + +- The first word starts with a lowercase letter +- Each following word starts with a capital letter +- There are no separators between words -var first = "Kings"; -var last = "road"; +Let's look at this in code: + +```java +var firstName = "John"; +System.out.println(firstName); // => John -var what = first + last; -System.out.print(what); // => "Kingsroad" +var playerNumber = 24; +System.out.println(playerNumber); // => 24 ``` + +## How not to do it + +You should not include the data type in a variable name. Such names are harder to read and quickly become outdated. For example, `userNameString` or `messagesNumber` describe not the meaning of the variable, but its technical implementation. + +A name should answer the question "what is stored?", not "what type is it?". That is why it is better to write `userName` instead of `userNameString` and `messagesCount` instead of `messagesNumber`. diff --git a/modules/30-variables/19-naming-style/en/data.yml b/modules/30-variables/19-naming-style/en/data.yml index 16d1485..9a82b67 100644 --- a/modules/30-variables/19-naming-style/en/data.yml +++ b/modules/30-variables/19-naming-style/en/data.yml @@ -1,10 +1,8 @@ --- -name: Variables and Concatenation +name: Naming variables tips: - - > - Consider with which line and in what order you need to glue the - modules.variables together in order to get such a two-line output of the - letter body. - - > - Remember that you can create a string that contains only the control - sequence `\n`. + - | + [Snake case](https://en.wikipedia.org/wiki/Snake_case) +definitions: + - name: Coding standard + description: a set of syntactic and stylistic rules for writing code. diff --git a/modules/30-variables/19-naming-style/es/EXERCISE.md b/modules/30-variables/19-naming-style/es/EXERCISE.md index bdedd50..43b6548 100644 --- a/modules/30-variables/19-naming-style/es/EXERCISE.md +++ b/modules/30-variables/19-naming-style/es/EXERCISE.md @@ -1,4 +1,8 @@ -Crea dos variables con los nombres "primerNumero" y "segundoNumero" en inglés, utilizando lowerCamelCase. Asigna el número `11` a la primera variable y `-100` a la segunda variable. Imprime en pantalla el producto de los números almacenados en las variables resultantes. +Crea dos variables con los nombres «primer número» y «segundo número» en inglés, utilizando lowerCamelCase. Escribe el número `11` en la primera variable y `-100` en la segunda. Imprime en pantalla el producto de los números almacenados en las variables resultantes. -El código funcionará con cualquier nombre, y nuestro sistema siempre verifica solo el resultado en pantalla, por lo que la ejecución de esta tarea es responsabilidad tuya. +```text +-1100 +``` + +El código funcionará con cualquier nombre, y nuestro sistema siempre verifica solo el resultado en pantalla, por lo que completar esta tarea es tu responsabilidad. diff --git a/modules/30-variables/19-naming-style/es/README.md b/modules/30-variables/19-naming-style/es/README.md index f7e7aa6..e9a6f73 100644 --- a/modules/30-variables/19-naming-style/es/README.md +++ b/modules/30-variables/19-naming-style/es/README.md @@ -1,23 +1,52 @@ +`greeting` sirve como ejemplo de un nombre de variable simple y claro. Pero a menudo nombres como `name`, `email` o `price` resultan insuficientes. Por ejemplo, hay que describir el nombre de un usuario, la cantidad total de pedidos, la longitud máxima de un mensaje. Esos nombres ya constan de varias palabras. ¿Cómo se verá el nombre de la variable en ese caso? -`greeting` - es un ejemplo de un nombre simple, pero no todos los nombres son tan simples. Con frecuencia, los nombres de las variables son compuestos, es decir, incluyen varias palabras. Por ejemplo, "nombre de usuario". En diferentes lenguajes de programación se utilizan diferentes convenciones de codificación, por lo que el nombre de la variable puede variar. +En los distintos lenguajes de programación se usan diferentes estilos de nomenclatura. De eso depende cómo se verá un nombre compuesto. Por ejemplo, así se puede escribir una variable que almacena la longitud máxima de un mensaje: -En la nomenclatura de variables se pueden identificar cuatro enfoques principales, que a veces se combinan entre sí. Todos estos enfoques se aplican cuando el nombre de la variable consta de varias palabras: +1. `maxmessagelength` +1. `maxMessageLength` +1. `max-message-length` +1. `max_message_length` -* kebab-case - las partes compuestas de la variable se separan con guiones (`mi-super-var`) -* snake_case - se utiliza un guion bajo para separar las palabras (`mi_super_var`) -* CamelCase - cada palabra en la variable se escribe con mayúscula inicial (`MiSuperVar`) -* lowerCamelCase - cada palabra en la variable se escribe con mayúscula inicial, excepto la primera (`miSuperVar`) +## Estilos principales -En Java se utiliza CamelCase y su variante lowerCamelCase, donde la primera letra de la primera palabra es minúscula. +En la nomenclatura de variables se pueden distinguir cuatro enfoques principales. Todos ellos se manifiestan cuando el nombre consta de varias palabras: -Es precisamente lowerCamelCase el que se utiliza para las variables. Esto significa que los nombres se unen entre sí, y todas las palabras, excepto la primera, se escriben con mayúscula inicial: `nombreDeUsuario`. Con tres palabras, se vería así: `miSuperVariable`. +- kebab-case: las palabras se separan con un guion, por ejemplo `max-message-length`. -Veamos cómo se ve esto en el código: + No funciona en Java, porque el guion se interpreta como el operador de resta. + +- snake_case: las palabras se separan con un guion bajo, por ejemplo `max_message_length`. + +- CamelCase (o UpperCamelCase): cada palabra con mayúscula inicial y sin separadores, por ejemplo `MaxMessageLength`. + +- lowerCamelCase: lo mismo, pero la primera palabra empieza con minúscula, por ejemplo `maxMessageLength`. + +## Cómo hacerlo correctamente en Java + +Para los nombres de variables en Java se adopta el estilo lowerCamelCase. Las palabras se unen entre sí, y cada palabra, excepto la primera, se escribe con mayúscula inicial: ```java -var primerNombre = "John"; -System.out.println(primerNombre); // => John +var userName = "Daenerys"; +var maxLength = 280; +var totalOrdersCount = 17; +``` + +- La primera palabra empieza con minúscula +- Cada palabra siguiente empieza con mayúscula +- No hay separadores entre las palabras -var numeroJugador = 24; -System.out.println(numeroJugador); // => 24 +Veámoslo en el código: + +```java +var firstName = "John"; +System.out.println(firstName); // => John + +var playerNumber = 24; +System.out.println(playerNumber); // => 24 ``` + +## Cómo no hacerlo + +No conviene incluir el tipo de dato en el nombre de la variable. Esos nombres se leen peor y se quedan obsoletos rápidamente. Por ejemplo, `userNameString` o `messagesNumber` describen no el significado de la variable, sino su implementación técnica. + +El nombre debe responder a la pregunta "¿qué se almacena?", y no "¿de qué tipo es?". Por eso es mejor escribir `userName` en lugar de `userNameString` y `messagesCount` en lugar de `messagesNumber`. diff --git a/modules/30-variables/19-naming-style/es/data.yml b/modules/30-variables/19-naming-style/es/data.yml index fe057a9..221eb72 100644 --- a/modules/30-variables/19-naming-style/es/data.yml +++ b/modules/30-variables/19-naming-style/es/data.yml @@ -1,6 +1,8 @@ --- name: Nomenclatura de variables -tips: [] +tips: + - | + [Snake case](https://es.wikipedia.org/wiki/Snake_case) definitions: - - name: Convención de codificación - description: Un conjunto de reglas sintácticas y estilísticas para escribir código. + - name: Estándar de codificación + description: un conjunto de reglas sintácticas y estilísticas para escribir código. diff --git a/modules/30-variables/23-constants/en/EXERCISE.md b/modules/30-variables/23-constants/en/EXERCISE.md index 1f6490a..cab2e27 100644 --- a/modules/30-variables/23-constants/en/EXERCISE.md +++ b/modules/30-variables/23-constants/en/EXERCISE.md @@ -1,2 +1,2 @@ -Create the constant `dragonsBornCount` and write the number 3 in it - the number of dragons born to Dayenerys. Print the value of the constant to the screen. +Create a constant `dragonsBornCount` and write the number 3 into it — this is the number of dragons born to Daenerys. Print the value of the constant to the screen. diff --git a/modules/30-variables/23-constants/en/README.md b/modules/30-variables/23-constants/en/README.md index dc15ccb..bc7c619 100644 --- a/modules/30-variables/23-constants/en/README.md +++ b/modules/30-variables/23-constants/en/README.md @@ -1,11 +1,58 @@ +Sometimes a program has values that should never change. For example: -Some data, such as mathematical constants, never changes. Take the number π. Approximately it is always equal to `3.14` and cannot change. +- The mathematical constant π (pi). +- The dollar exchange rate on a certain date. +- A fixed service fee. -To access such data in Java, it is customary to use constants. +Such values are called constants, and it is customary to distinguish them from ordinary variables so that there is no temptation to change them. + +## Example: the number π + +Take the number π. Approximately it is always equal to *3.14* and cannot change: ```java final var pi = 3.14; -System.out.print(pi); // 3.14 +System.out.println(pi); // => 3.14 ``` -A constant, like a variable, can be used in any expression. The only restriction is that the constant cannot be changed, which sounds quite logical. +Here `pi` will be a constant that stores the value of the number π. The point of a constant is that its value does not change while the program runs. + +## How a constant differs from a variable + +The concept of constants is common in most programming languages. In Java, the keyword `final` is placed before the definition of a constant. It tells the compiler that changes are forbidden. Any attempt to change a constant will lead to an error: + +```java +final var pi = 3.14; +pi = 3.14159; +// Error: +// cannot assign a value to final variable pi +// cannot assign a value to the constant pi +``` + +The compiler finds such an error without running the code. This is the strength of `final`: the language itself makes sure that the value stays unchanged. + +## How constants are written + +A constant, like a variable, can be used in any expression. The only restriction is that it cannot be changed. + +When a constant is described at the level of the whole class and is available to the entire program, Java adopts a special style for writing the name: + +- All letters are uppercase +- Words are separated by an underscore `_` +- The style is called UPPER_SNAKE_CASE (it is also called SCREAMING_SNAKE_CASE) + +Such constants are usually declared with `static final`: + +```java +static final double PI = 3.14; +static final int MAX_USERS = 100; +static final int DEFAULT_TIMEOUT = 30; +``` + +From the name it is immediately clear that this is a constant, not an ordinary variable. The uppercase letters make it stand out in the code. + +## Why constants are needed + +Constants make code clearer and safer. They help you see right away which values in the program are considered fixed and should not change. This is especially important when working with mathematical and physical constants, default settings, or fixed limits. + +Using constants reduces the risk of errors. Thanks to the `final` keyword, the compiler will not let you accidentally change the value. In addition, if the value does need to be changed, for example in the settings, it is enough to fix it in one place, and the change will be picked up throughout the whole program. diff --git a/modules/30-variables/23-constants/en/data.yml b/modules/30-variables/23-constants/en/data.yml index 0fe7bb3..36f5981 100644 --- a/modules/30-variables/23-constants/en/data.yml +++ b/modules/30-variables/23-constants/en/data.yml @@ -1,2 +1,8 @@ --- name: Constants +tips: [] +definitions: + - name: Constant + description: >- + a way to store information and give it a name for later use in the code; + constants cannot be changed, unlike variables. diff --git a/modules/30-variables/23-constants/es/EXERCISE.md b/modules/30-variables/23-constants/es/EXERCISE.md index 0c034fd..03857fc 100644 --- a/modules/30-variables/23-constants/es/EXERCISE.md +++ b/modules/30-variables/23-constants/es/EXERCISE.md @@ -1,2 +1,2 @@ -Crea una constante llamada `dragonsBornCount` y asígnale el valor de 3, que es la cantidad de dragones que nacieron de Daenerys. Muestra el valor de la constante en pantalla. +Crea una constante `dragonsBornCount` y escribe en ella el número 3, que es la cantidad de dragones que nacieron de Daenerys. Muestra el valor de la constante en pantalla. diff --git a/modules/30-variables/23-constants/es/README.md b/modules/30-variables/23-constants/es/README.md index 7db0575..27374d8 100644 --- a/modules/30-variables/23-constants/es/README.md +++ b/modules/30-variables/23-constants/es/README.md @@ -1,12 +1,58 @@ -Algunos datos nunca cambian, como las constantes matemáticas. Tomemos el número *π*. Aproximadamente siempre es igual a *3.14* y no puede cambiar. +A veces en un programa aparecen valores que nunca deben cambiar. Por ejemplo: -En Java, se acostumbra utilizar constantes para acceder a este tipo de datos: +- La constante matemática π (pi). +- El tipo de cambio del dólar en una fecha determinada. +- La comisión fija de un servicio. + +Esos valores se llaman constantes, y se acostumbra distinguirlos de las variables corrientes para que no surja la tentación de cambiarlos. + +## Ejemplo: el número π + +Tomemos el número π. Aproximadamente siempre es igual a *3.14* y no puede cambiar: ```java final var pi = 3.14; -System.out.println(pi); // 3.14 +System.out.println(pi); // => 3.14 ``` -A diferencia de las variables, al definir una constante se utiliza la palabra clave `final`. Esto le indica al compilador que no se puede modificar. Cualquier intento de cambiar una constante resultará en un error. +Aquí `pi` será una constante que almacena el valor del número π. El sentido de una constante es que su valor no cambia durante la ejecución del programa. + +## En qué se diferencia una constante de una variable + +El concepto de constante es común en la mayoría de los lenguajes de programación. En Java, antes de la definición de una constante se coloca la palabra clave `final`. Le indica al compilador la prohibición de modificarla. Cualquier intento de cambiar una constante provocará un error: + +```java +final var pi = 3.14; +pi = 3.14159; +// Error: +// cannot assign a value to final variable pi +// no se puede asignar un valor a la constante pi +``` + +El compilador encuentra ese error sin ejecutar el código. En eso está la fuerza de `final`: el propio lenguaje se encarga de que el valor permanezca invariable. + +## Cómo se escriben las constantes + +Una constante, al igual que una variable, puede usarse en cualquier expresión. La única restricción es que no se puede cambiar. + +Cuando una constante se describe a nivel de toda la clase y está disponible para todo el programa, en Java se adopta un estilo especial para escribir el nombre: + +- Todas las letras en mayúscula +- Las palabras se separan con un guion bajo `_` +- El estilo se llama UPPER_SNAKE_CASE (también se le llama SCREAMING_SNAKE_CASE) + +Esas constantes suelen declararse con `static final`: + +```java +static final double PI = 3.14; +static final int MAX_USERS = 100; +static final int DEFAULT_TIMEOUT = 30; +``` + +Por el nombre se ve enseguida que estamos ante una constante, y no una variable corriente. Las mayúsculas la destacan en el código. + +## Para qué sirven las constantes + +Las constantes hacen que el código sea más claro y seguro. Ayudan a ver de inmediato qué valores del programa se consideran fijos y no deben cambiar. Esto es especialmente importante al trabajar con constantes matemáticas y físicas, ajustes por defecto o límites fijos. -Una constante, al igual que una variable, puede ser utilizada en cualquier expresión. La única restricción es que no se puede modificar una constante, lo cual tiene bastante sentido. +El uso de constantes reduce el riesgo de errores. Gracias a la palabra clave `final`, el compilador no permitirá cambiar el valor por accidente. Además, si aun así hay que cambiar el valor, por ejemplo en los ajustes, basta con corregirlo en un solo lugar, y el cambio se aplicará en todo el programa. diff --git a/modules/30-variables/23-constants/es/data.yml b/modules/30-variables/23-constants/es/data.yml index 9158b23..fe9897e 100644 --- a/modules/30-variables/23-constants/es/data.yml +++ b/modules/30-variables/23-constants/es/data.yml @@ -1,2 +1,9 @@ --- name: Constantes +tips: [] +definitions: + - name: Constante + description: >- + una forma de guardar información y darle un nombre para su uso posterior en + el código; las constantes no se pueden cambiar, a diferencia de las + variables. diff --git a/modules/30-variables/description.en.yml b/modules/30-variables/description.en.yml index 6d06b5a..e3fe716 100644 --- a/modules/30-variables/description.en.yml +++ b/modules/30-variables/description.en.yml @@ -2,4 +2,4 @@ name: Variables description: | -  Information can be placed in special "storage", and then use as many times as necessary. These storages are called modules.variables, and they help simplify the code and reduce unnecessary repetitions. + Information can be placed in special "storages" — variables. This lets you reuse existing data and avoid duplicating it in different parts of the code. In this module, we will look at how to change variables and name them so that reading your code is clear to any developer. You will realize that coming up with a variable name is not so simple! We will also explain how to use variables to simplify complex calculations.