diff --git a/modules/35-methods-using/140-string-substring/en/README.md b/modules/35-methods-using/140-string-substring/en/README.md index 1f4625b..6a5a7b5 100644 --- a/modules/35-methods-using/140-string-substring/en/README.md +++ b/modules/35-methods-using/140-string-substring/en/README.md @@ -21,7 +21,9 @@ System.out.println(year); // => 2034 The method is called on the string through a dot. The first argument sets the start index, the second sets the end index. The call format is: -```java +This schematic notation shows the order of the arguments. + +```text string.substring(start, end) ``` @@ -31,8 +33,8 @@ The character at the start index is included in the result, but the character at var value = "code-basics"; System.out.println(value.substring(5, 11)); // => basics (indexes 5 through 10) -System.out.println(value.substring(0, 7)); // => code-ba (indexes 0 through 6) -System.out.println(value.substring(2, 6)); // => de-b +System.out.println(value.substring(0, 7)); // => code-ba (indexes 0 through 6) +System.out.println(value.substring(2, 6)); // => de-b ``` How do you count all this? When working with a specific string, we almost always count by eye. @@ -64,7 +66,7 @@ The call `value.substring(3)` takes characters from index `3` and further to the ## Going out of the string bounds -The indexes must fall inside the string. If you pass an index greater than the string length, the method throws an error: +The boundaries must range from zero to the string length, inclusive, and the start must not exceed the end. If you pass an index greater than the string length, the method throws an error: ```java var value = "Hexlet"; @@ -75,3 +77,5 @@ System.out.println(value.substring(0, 10)); The string `"Hexlet"` has six characters, so the end index cannot be greater than `6`. We passed `10`, and the method terminated with a `StringIndexOutOfBoundsException` error. Before the call, you should make sure that the indexes are within the string bounds. The main thing is to understand the basic structure `string.substring(start, end)`, and in practice these calls will quickly become a habit. + +For `substring(begin, end)`, the end boundary `end` can equal the length of the string because the character at that boundary is excluded from the result. The start boundary can also equal the length. For example, `"Hexlet".substring(6)` returns the empty string `""`. diff --git a/modules/35-methods-using/140-string-substring/es/README.md b/modules/35-methods-using/140-string-substring/es/README.md index 1ed316d..68f93e3 100644 --- a/modules/35-methods-using/140-string-substring/es/README.md +++ b/modules/35-methods-using/140-string-substring/es/README.md @@ -21,7 +21,9 @@ System.out.println(year); // => 2034 El método se llama en la cadena a través de un punto. El primer argumento indica el índice de inicio, el segundo indica el índice de fin. El formato de la llamada es así: -```java +Esta escritura esquemática muestra el orden de los argumentos. + +```text cadena.substring(inicio, fin) ``` @@ -31,8 +33,8 @@ El carácter con el índice de inicio se incluye en el resultado, pero el carác var value = "code-basics"; System.out.println(value.substring(5, 11)); // => basics (del índice 5 al 10) -System.out.println(value.substring(0, 7)); // => code-ba (del índice 0 al 6) -System.out.println(value.substring(2, 6)); // => de-b +System.out.println(value.substring(0, 7)); // => code-ba (del índice 0 al 6) +System.out.println(value.substring(2, 6)); // => de-b ``` ¿Cómo se calcula todo esto? Cuando trabajamos con una cadena concreta, casi siempre lo calculamos a ojo. @@ -64,7 +66,7 @@ La llamada `value.substring(3)` toma los caracteres desde el índice `3` y en ad ## Salida fuera de los límites de la cadena -Los índices deben caer dentro de la cadena. Si pasas un índice mayor que la longitud de la cadena, el método lanza un error: +Los límites deben estar entre cero y la longitud de la cadena, inclusive, y el inicio no debe superar el fin. Si pasas un índice mayor que la longitud de la cadena, el método lanza un error: ```java var value = "Hexlet"; @@ -75,3 +77,5 @@ System.out.println(value.substring(0, 10)); La cadena `"Hexlet"` tiene seis caracteres, por lo que el índice de fin no puede ser mayor que `6`. Pasamos `10`, y el método terminó con el error `StringIndexOutOfBoundsException`. Antes de la llamada, conviene asegurarse de que los índices estén dentro de los límites de la cadena. Lo principal es entender la estructura básica `cadena.substring(inicio, fin)`, y en la práctica estas llamadas se convertirán rápidamente en un hábito. + +En `substring(begin, end)`, el límite final `end` puede ser igual a la longitud de la cadena, porque el carácter de ese límite no se incluye en el resultado. El límite inicial también puede ser igual a la longitud. Por ejemplo, `"Hexlet".substring(6)` devuelve la cadena vacía `""`. diff --git a/modules/35-methods-using/300-variadic-parameters/en/README.md b/modules/35-methods-using/300-variadic-parameters/en/README.md index e871ea3..e5162f3 100644 --- a/modules/35-methods-using/300-variadic-parameters/en/README.md +++ b/modules/35-methods-using/300-variadic-parameters/en/README.md @@ -35,3 +35,5 @@ The notation `String...` means "zero or more strings". Required parameters (like ## Why it's needed A variable number of parameters makes methods flexible. There is no need to create separate methods `join2()`, `join3()`, `join4()` for each number of strings — one method is enough, which accepts any number of them. This removes duplication and simplifies working with the standard library: a huge number of its methods are designed precisely for a variable number of arguments. + +The simplified notation `String.join(String delimiter, String... values)` shows the method parameters for string arguments. Here, `delimiter` takes one separator string, and `values` takes the strings to join. In `String.join(":", "8", "30", "00")`, `":"` is the separator, and the other three arguments belong to `values`. You can call this method without declaring your own, since it already belongs to the `String` class. diff --git a/modules/35-methods-using/300-variadic-parameters/es/README.md b/modules/35-methods-using/300-variadic-parameters/es/README.md index c4271e3..1e3da99 100644 --- a/modules/35-methods-using/300-variadic-parameters/es/README.md +++ b/modules/35-methods-using/300-variadic-parameters/es/README.md @@ -35,3 +35,5 @@ La notación `String...` significa "cero o más cadenas". Los parámetros obliga ## Para qué sirve El número variable de parámetros hace que los métodos sean flexibles. No hay que crear métodos separados `join2()`, `join3()`, `join4()` para cada cantidad de cadenas: basta con un solo método que acepte cualquier cantidad de ellas. Esto elimina la duplicación y simplifica el trabajo con la biblioteca estándar: una enorme cantidad de sus métodos está diseñada precisamente para un número variable de argumentos. + +La escritura simplificada `String.join(String delimiter, String... values)` muestra los parámetros del método para argumentos de tipo cadena. Aquí `delimiter` recibe una cadena separadora y `values` recibe las cadenas que se unen. En `String.join(":", "8", "30", "00")`, `":"` es el separador y los otros tres argumentos corresponden a `values`. No hace falta declarar un método propio para esta llamada, ya que forma parte de la clase `String`. diff --git a/modules/35-methods-using/400-stdlib/en/README.md b/modules/35-methods-using/400-stdlib/en/README.md index 23d662e..d78341d 100644 --- a/modules/35-methods-using/400-stdlib/en/README.md +++ b/modules/35-methods-using/400-stdlib/en/README.md @@ -7,3 +7,5 @@ Here are some tips on how to learn about new methods: - Always clearly track which data type you are currently working with. Almost always you will find the needed method in the corresponding section of the documentation — for example, to work with strings you need to study string methods - Periodically open the section with standard methods for the topic you are studying and simply skim through them, studying signatures and ways of use - Read other people's code more often, especially the code of the libraries you use. It is all available on GitHub + +Suppose you need to remove spaces from the ends of a string. Start with the [documentation for the `String` class](https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/lang/String.html). The Method Summary section lists methods with short descriptions. It describes `trim()` as returning a string without leading or trailing spaces. Follow the `trim()` link to read the detailed contract. Calling `trim()` on `" Java "` returns `"Java"`. Numeric operations, such as the absolute value of a number, appear in the [documentation for the `Math` class](https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/lang/Math.html). diff --git a/modules/35-methods-using/400-stdlib/es/README.md b/modules/35-methods-using/400-stdlib/es/README.md index 6555065..2312b5e 100644 --- a/modules/35-methods-using/400-stdlib/es/README.md +++ b/modules/35-methods-using/400-stdlib/es/README.md @@ -7,3 +7,5 @@ Aquí hay algunos consejos sobre cómo aprender sobre nuevos métodos: - Siempre sigue claramente el tipo de datos con el que estás trabajando. Casi siempre encontrarás el método necesario en la sección correspondiente de la documentación, por ejemplo, para trabajar con cadenas, debes estudiar los métodos de cadena. - Abre periódicamente la sección de métodos estándar relacionados con el tema que estás estudiando y simplemente revísalos, estudiando las firmas y formas de uso. - Lee el código de otras personas con más frecuencia, especialmente el código de las bibliotecas que estás utilizando. Todo está disponible en GitHub. + +Supongamos que hay que quitar los espacios de los extremos de una cadena. Para buscar el método sirve la [documentación de la clase `String`](https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/lang/String.html). La sección Method Summary muestra los métodos con descripciones breves. Allí `trim()` se describe como un método que devuelve una cadena sin espacios iniciales ni finales. Su enlace abre el contrato detallado. Para `" Java "`, la llamada a `trim()` devuelve `"Java"`. Las operaciones numéricas, como el valor absoluto, se encuentran en la [documentación de la clase `Math`](https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/lang/Math.html). diff --git a/modules/45-logic/90-logical-expressions/en/README.md b/modules/45-logic/90-logical-expressions/en/README.md index 547c9ec..155ec8f 100644 --- a/modules/45-logic/90-logical-expressions/en/README.md +++ b/modules/45-logic/90-logical-expressions/en/README.md @@ -10,31 +10,35 @@ A compound logical expression in Java always evaluates to `true` or `false`. The ## The order of evaluation -Arithmetic, comparisons and logical operators occur in one expression. Java evaluates them in a strict order of priorities: +Arithmetic, comparisons and logical operators occur in one expression. Priority determines how the operators are grouped in the expression: ```text Priority (from high to low): () parentheses ↓ - * / % + - arithmetic + ! negation ↓ - < <= > >= == != comparisons + * / % multiplication, division, remainder ↓ - ! negation + + - addition, subtraction + ↓ + < <= > >= numeric comparisons + ↓ + == != equality ↓ && logical AND ↓ || logical OR ``` -First the arithmetic is calculated, then the comparisons give `true` or `false`, and only after that the logical operators join these values. The `&&` operator is true when both operands are true. The `||` operator is true when at least one is true. The `!` operator changes a value to the opposite one. +Arithmetic has higher priority than comparisons, and comparisons bind more tightly than `&&` and `||`. Negation `!` has higher priority than comparisons. Thus, `!true == false` means `(!true) == false`. To negate the result of a comparison, use parentheses, as in `!(age >= 18)`. The operands themselves are evaluated from left to right, respecting short-circuit evaluation. The `&&` operator is true when both operands are true. The `||` operator is true when at least one is true. The `!` operator changes a value to the opposite one. ## Evaluation step by step Let's take apart the expression from the example above. We have `age` equal to `20`, and `hasConsent` equal to `true`: -```java +```text age >= 18 && hasConsent 20 >= 18 && true // we substituted the values of the variables true && true // the comparison 20 >= 18 gave true @@ -60,7 +64,7 @@ true // all the operands of && are true ## Parentheses and priority -When `&&` and `||` are mixed in an expression, the order is set by parentheses. Without them `&&` is applied earlier than `||`, and the meaning may turn out not to be the intended one: +When `&&` and `||` are mixed in an expression, the order is set by parentheses. Without them, `&&` binds its operands more tightly than `||`, and the meaning may turn out not to be the intended one: ```java // && binds b and c, so this is a || (b && c) @@ -70,7 +74,7 @@ System.out.println(true || false && false); // => true System.out.println((true || false) && false); // => false ``` -The first expression first evaluates `false && false`, gets `false`, and then `true || false` gives `true`. In the second case the parentheses force `true || false` to be evaluated first, this gives `true && false`, and the result is `false`. +In the first expression, `&&` groups the right-hand part, but this part is skipped. The left operand of `||` is already `true`, so the whole expression evaluates to `true`. In the second case the parentheses force `true || false` to be evaluated first, this gives `true && false`, and the result is `false`. ## Short-circuit evaluation diff --git a/modules/45-logic/90-logical-expressions/es/README.md b/modules/45-logic/90-logical-expressions/es/README.md index e4ef5ca..90c5dc6 100644 --- a/modules/45-logic/90-logical-expressions/es/README.md +++ b/modules/45-logic/90-logical-expressions/es/README.md @@ -10,31 +10,35 @@ Una expresión lógica compuesta en Java siempre se evalúa a `true` o a `false` ## El orden de evaluación -En una misma expresión coinciden aritmética, comparaciones y operadores lógicos. Java los evalúa en un orden estricto de prioridades: +En una misma expresión coinciden aritmética, comparaciones y operadores lógicos. La prioridad determina cómo se agrupan los operadores en la expresión: ```text Prioridad (de la más alta a la más baja): () paréntesis ↓ - * / % + - aritmética + ! negación ↓ - < <= > >= == != comparaciones + * / % multiplicación, división, resto ↓ - ! negación + + - suma, resta + ↓ + < <= > >= comparación de números + ↓ + == != igualdad ↓ && Y lógico ↓ || O lógico ``` -Primero se calcula la aritmética, después las comparaciones dan `true` o `false`, y solo entonces los operadores lógicos unen esos valores. El operador `&&` es verdadero cuando son verdaderos los dos operandos. El operador `||` es verdadero cuando es verdadero al menos uno. El operador `!` cambia el valor por el contrario. +La aritmética tiene mayor prioridad que las comparaciones, y las comparaciones se agrupan antes que `&&` y `||`. La negación `!` tiene mayor prioridad que las comparaciones. Por eso `!true == false` significa `(!true) == false`. Para negar el resultado de una comparación hacen falta paréntesis, por ejemplo `!(age >= 18)`. Los operandos se evalúan de izquierda a derecha, respetando la evaluación abreviada. El operador `&&` es verdadero cuando son verdaderos los dos operandos. El operador `||` es verdadero cuando es verdadero al menos uno. El operador `!` cambia el valor al opuesto. ## La evaluación paso a paso Analicemos la expresión del ejemplo de arriba. Tenemos `age` igual a `20` y `hasConsent` igual a `true`: -```java +```text age >= 18 && hasConsent 20 >= 18 && true // sustituimos los valores de las variables true && true // la comparación 20 >= 18 dio true @@ -60,7 +64,7 @@ true // todos los operandos de && son verdaderos ## Los paréntesis y la prioridad -Cuando en una expresión se mezclan `&&` y `||`, el orden lo marcan los paréntesis. Sin ellos, `&&` se aplica antes que `||`, y el sentido puede no ser el que se pretendía: +Cuando en una expresión se mezclan `&&` y `||`, el orden lo marcan los paréntesis. Sin ellos, `&&` agrupa sus operandos con mayor prioridad que `||`, y el sentido puede no ser el que se pretendía: ```java // && une b y c, por eso esto es a || (b && c) @@ -70,7 +74,7 @@ System.out.println(true || false && false); // => true System.out.println((true || false) && false); // => false ``` -La primera expresión calcula primero `false && false`, obtiene `false`, y después `true || false` da `true`. En el segundo caso los paréntesis obligan a calcular `true || false` primero, sale `true && false`, y el resultado es `false`. +En la primera expresión, `&&` agrupa la parte derecha, pero esta no se evalúa. El operando izquierdo de `||` ya es `true`, por lo que el resultado de toda la expresión es `true`. En el segundo caso, los paréntesis obligan a calcular `true || false` primero, sale `true && false`, y el resultado es `false`. ## La evaluación abreviada diff --git a/modules/90-loops/450-mutators/en/README.md b/modules/90-loops/450-mutators/en/README.md index 47902d6..f0336ba 100644 --- a/modules/90-loops/450-mutators/en/README.md +++ b/modules/90-loops/450-mutators/en/README.md @@ -32,10 +32,10 @@ The rule works the same way for increment and decrement. For simplicity let's co var x = 5; System.out.println(++x); // => 6 -System.out.println(x); // => 6 +System.out.println(x); // => 6 System.out.println(x++); // => 6 -System.out.println(x); // => 7 +System.out.println(x); // => 7 ``` What happens in the code above: @@ -47,6 +47,8 @@ What happens in the code above: It becomes especially complicated when an increment is inserted inside other operations: `x = i++ - 7 + --h`. It is almost impossible to understand such code. +A side effect is a change of state in addition to producing the result of an expression. For `x++`, it is the change to the variable `x` itself. For example, after `var height = x++`, `height` holds the previous value of `x`, and `x` has increased by one. You therefore need to track the expression result and the variable state separately. + Recommendations for use: - Never mix operations without side effects with operations with side effects. The same goes for methods diff --git a/modules/90-loops/450-mutators/es/README.md b/modules/90-loops/450-mutators/es/README.md index 90cc56c..abe27c4 100644 --- a/modules/90-loops/450-mutators/es/README.md +++ b/modules/90-loops/450-mutators/es/README.md @@ -32,10 +32,10 @@ La regla funciona de la misma manera para el incremento y el decremento. Para si var x = 5; System.out.println(++x); // => 6 -System.out.println(x); // => 6 +System.out.println(x); // => 6 System.out.println(x++); // => 6 -System.out.println(x); // => 7 +System.out.println(x); // => 7 ``` Lo que sucede en el código anterior: @@ -47,6 +47,8 @@ Lo que sucede en el código anterior: Se vuelve especialmente complicado cuando se inserta el incremento en otras operaciones: `x = i++ - 7 + --h`. Es casi imposible entender un código así. +Un efecto secundario es un cambio de estado además de obtener el resultado de una expresión. En `x++` es el cambio de la propia variable `x`. Por ejemplo, después de `var height = x++`, `height` contiene el valor anterior de `x` y `x` ya ha aumentado en uno. Por eso hay que considerar por separado el resultado de la expresión y el estado de la variable. + Recomendaciones de uso: - Nunca mezcles operaciones sin efectos secundarios con operaciones con efectos secundarios. Lo mismo se aplica a los métodos.