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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions modules/45-logic/10-bool-type/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

Implement the method `isPensioner()`, which accepts one parameter — a person's age — and checks whether it is the retirement age. A person who has reached the age of 60 and above is considered a pensioner.

Examples of calls:

```java
App.isPensioner(75); // true
App.isPensioner(18); // false
```
78 changes: 78 additions & 0 deletions modules/45-logic/10-bool-type/en/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
Besides arithmetic operations, from school mathematics we also know comparison operations, for example `5 > 4` or `3 < 1`. They exist in programming as well. Comparisons are often used in real tasks related to numbers. When we place an order in an online store, the system checks whether the user has enough money in their account. If the amount in the account is greater than or equal to the price of the product, the order is confirmed. If there are not enough funds, an error message appears.

## Comparison in programming

Let's start with an example in which two numbers are compared. We print the result of the comparison to the screen:

```java
System.out.println(5 > 4); // => true
System.out.println(4 > 4); // => false
```

The result of a comparison is a value of type `boolean`. This type has only two possible variants, `true` and `false`. These are special values of the language, and they can be printed directly:

```java
System.out.println(true); // => true
System.out.println(false); // => false
```

In practice they are rarely used this directly, but the logic of the program's behavior is built on top of them. We come across this every day, when we enter PIN codes and passwords, when we perform actions with different possible outcomes. All these variants are written inside the program in the form of conditional expressions. The program reasons roughly like this: *if it is this way, do one thing; if it is otherwise, do another*.

Check notice on line 19 in modules/45-logic/10-bool-type/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/45-logic/10-bool-type/en/README.md#L19

A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1]) Suggestions: `practice,` URL: http://englishplus.com/grammar/00000074.htm Rule: https://community.languagetool.org/rule/show/MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE?lang=en-US&subId=1 Category: PUNCTUATION
Raw output
modules/45-logic/10-bool-type/en/README.md:19:3: A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1])
 Suggestions: `practice,`
 URL: http://englishplus.com/grammar/00000074.htm 
 Rule: https://community.languagetool.org/rule/show/MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE?lang=en-US&subId=1
 Category: PUNCTUATION

The following comparison operations are available in Java:

* `<` — less than
* `<=` — less than or equal to
* `>` — greater than
* `>=` — greater than or equal to
* `==` — equal to
* `!=` — not equal to

Programming languages adapted all the mathematical comparison operations unchanged, except for the equality and inequality operators. In mathematics the usual `=` is used for equality, but in programming the `=` symbol assigns values to variables. That is why in Java comparison is done with the help of `==`. A few examples with the result printed to the screen:

```java
System.out.println(5 >= 3); // => true
System.out.println(7 < 0); // => false
System.out.println(5 > 5); // => false
System.out.println(5 >= 5); // => true
System.out.println(2 == 5); // => false
System.out.println(2 != 5); // => true
```

Any comparison operation can be saved in a variable of type `boolean` and then printed:

```java
boolean result = 5 > 4;
System.out.println(result); // => true
```

When the comparison contains hard-coded numbers, the operation seems meaningless. We already know its result, and it is always the same, because three is greater than two under any circumstances. The picture changes when the values come from outside. Let's write a method that accepts the age of a child and determines whether they are an infant. Children under one year old are considered infants:

Check notice on line 48 in modules/45-logic/10-bool-type/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/45-logic/10-bool-type/en/README.md#L48

It seems that hyphens are missing. (YEAR_OLD_HYPHEN[1]) Suggestions: `one-year-old` URL: https://languagetool.org/insights/post/hyphen/#hyphenated-numbers-and-fractions-numerals Rule: https://community.languagetool.org/rule/show/YEAR_OLD_HYPHEN?lang=en-US&subId=1 Category: PUNCTUATION
Raw output
modules/45-logic/10-bool-type/en/README.md:48:350: It seems that hyphens are missing. (YEAR_OLD_HYPHEN[1])
 Suggestions: `one-year-old`
 URL: https://languagetool.org/insights/post/hyphen/#hyphenated-numbers-and-fractions-numerals 
 Rule: https://community.languagetool.org/rule/show/YEAR_OLD_HYPHEN?lang=en-US&subId=1
 Category: PUNCTUATION

```java
public static boolean isInfant(int age) {
return age < 1;
}
```

With the single line of the method we write "return the value that results from the comparison `age < 1`". Depending on the argument that arrives, the comparison will be either true (`true`) or false (`false`). The method will return this result:

```java
System.out.println(App.isInfant(3)); // => false
System.out.println(App.isInfant(1)); // => false
System.out.println(App.isInfant(0)); // => true
```

## Predicates

When methods return the result of a comparison, they answer the question "yes" or "no". Such methods are called **predicates**. They are recognized by the fact that they return a logical value `true` or `false`. Often the name of a predicate contains a question or a statement that can be checked (`is`, `has`, `can`, `was`). Here is a method that checks whether a number is negative:

```java
public static boolean isNegative(int number) {
// We check whether the number is less than zero
return number < 0;
}

System.out.println(App.isNegative(-5)); // => true
System.out.println(App.isNegative(7)); // => false
```

The `isNegative` method gathers the condition inside and gives a short answer to the outside. This way the calculation is hidden behind an understandable name.
9 changes: 9 additions & 0 deletions modules/45-logic/10-bool-type/en/data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
name: The logical type
tips:
- >
[The boolean type in
Java](https://docs.oracle.com/javase/specs/jls/se21/html/jls-4.html#jls-4.2.5)
definitions:
- name: The logical type (boolean)
description: 'a data type with two possible values: true and false.'
78 changes: 46 additions & 32 deletions modules/45-logic/10-bool-type/es/README.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,78 @@
Además de las operaciones aritméticas, en matemáticas escolares también conocemos las operaciones de comparación, por ejemplo:
Además de las operaciones aritméticas, de las matemáticas escolares conocemos también las operaciones de comparación, por ejemplo `5 > 4` o `3 < 1`. También existen en programación. Las comparaciones se usan a menudo en tareas reales relacionadas con números. Cuando hacemos una compra en una tienda online, el sistema comprueba si al usuario le alcanza el dinero de su cuenta. Si el importe de la cuenta es mayor o igual que el precio del producto, el pedido se confirma. Si no hay fondos suficientes, aparece un mensaje de error.

```text
5 > 4
```
## La comparación en programación

Esto se lee como una pregunta: "¿Cinco es mayor que cuatro?". En este caso, la respuesta es "sí". En otros casos, la respuesta puede ser "no", por ejemplo, para la siguiente expresión:
Empecemos por un ejemplo en el que se comparan dos números. El resultado de la comparación lo mostramos en la pantalla:

```text
3 < 1
```java
System.out.println(5 > 4); // => true
System.out.println(4 > 4); // => false
```

Las operaciones de comparación no están limitadas a números. Se pueden comparar casi cualquier cosa, como cadenas de texto. Cuando ingresamos a un sitio web, se compara el nombre de usuario y la contraseña ingresados con los que están en la base de datos. Si hay una coincidencia, se realiza la autenticación.
El resultado de una comparación es un valor de tipo `boolean`. Este tipo tiene solo dos variantes posibles, `true` y `false`. Son valores especiales del lenguaje y se pueden mostrar directamente:

Los lenguajes de programación han adaptado todas las operaciones de comparación matemáticas prácticamente sin cambios. La única diferencia importante son los **operadores de igualdad y desigualdad**.
```java
System.out.println(true); // => true
System.out.println(false); // => false
```

En matemáticas, se utiliza el signo de igual `=`, pero en programación esto no se encuentra con frecuencia. En muchos lenguajes, el símbolo `=` se utiliza para asignar valores a variables, por lo que se utiliza `==` para las comparaciones.
En la práctica se usan pocas veces así, de forma tan directa, pero sobre ellos se construye la lógica del comportamiento del programa. Nos topamos con esto cada día, cuando introducimos códigos PIN y contraseñas, cuando realizamos acciones con distintos desenlaces posibles. Todas esas variantes están escritas dentro del programa en forma de expresiones condicionales. El programa razona más o menos así: *si es así, haz una cosa; si es de otra manera, haz otra*.

Aquí tienes una lista de las operaciones de comparación en Java:
En Java están disponibles las siguientes operaciones de comparación:

* `<` — menor que
* `<=` — menor o igual que
* `>` — mayor que
* `>=` — mayor o igual que
* `==` — igual que
* `!=` — no igual que
* `!=` — distinto de

Veamos algunos ejemplos de operaciones lógicas:
Los lenguajes de programación adaptaron todas las operaciones matemáticas de comparación sin cambios, excepto los operadores de igualdad y desigualdad. En matemáticas, para la igualdad se usa el habitual `=`, pero en programación el símbolo `=` asigna valores a las variables. Por eso en Java se compara con la ayuda de `==`. Unos cuantos ejemplos mostrando el resultado en la pantalla:

Check notice on line 30 in modules/45-logic/10-bool-type/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/45-logic/10-bool-type/es/README.md#L30

If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE) Suggestions: `Java SE` URL: https://languagetool.org/insights/post/spelling-capital-letters/ Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US Category: CASING
Raw output
modules/45-logic/10-bool-type/es/README.md:30:251: If the term is a proper noun, use initial capitals. (EN_SPECIFIC_CASE)
 Suggestions: `Java SE`
 URL: https://languagetool.org/insights/post/spelling-capital-letters/ 
 Rule: https://community.languagetool.org/rule/show/EN_SPECIFIC_CASE?lang=en-US
 Category: CASING

```text
5 > 4
password == text
```java
System.out.println(5 >= 3); // => true
System.out.println(7 < 0); // => false
System.out.println(5 > 5); // => false
System.out.println(5 >= 5); // => true
System.out.println(2 == 5); // => false
System.out.println(2 != 5); // => true
```

Ambos ejemplos son expresiones. El resultado de evaluar estas expresiones es uno de los dos valores especiales:
Cualquier operación de comparación se puede guardar en una variable de tipo `boolean` y después mostrarla:

* `true` — "verdadero"
* `false`— "falso"
```java
boolean result = 5 > 4;
System.out.println(result); // => true
```

Este es un nuevo tipo de dato para nosotros, llamado **booleano**. Solo puede tener estos dos valores. Aquí tienes un ejemplo de código que lo utiliza:
Cuando en la comparación hay números fijos, la operación parece no tener sentido. Ya conocemos su resultado, y siempre es el mismo, porque tres es mayor que dos en cualquier circunstancia. El panorama cambia cuando los valores llegan de fuera. Escribamos un método que recibe la edad de un niño y determina si es un bebé. Se consideran bebés los niños de menos de un año:

```java
var resultado = 5 > 4;
System.out.println(resultado); // => true
public static boolean isInfant(int age) {
return age < 1;
}
```

Intentemos escribir un método que tome la edad de un niño y determine si es un bebé. Se considera bebé a un niño menor de un año:
Con la única línea del método escribimos "devolver el valor que resulte de la comparación `age < 1`". Según el argumento que llegue, la comparación será verdadera (`true`) o falsa (`false`). El método devolverá ese resultado:

```java
// Un método que devuelve un booleano se llama predicado
// Por lo general, estos métodos tienen un prefijo como has, can, is, was, etc.
public static boolean esBebe(int edad) {
return edad < 1;
}
System.out.println(App.isInfant(3)); // => false
System.out.println(App.isInfant(1)); // => false
System.out.println(App.isInfant(0)); // => true
```

Aprovechamos el hecho de que cualquier operación es una expresión. Por lo tanto, en una sola línea de la función, escribimos "devolver el resultado de la comparación `edad < 1`".
## Predicados

Dependiendo del parámetro recibido, la comparación será verdadera (`true`) o falsa (`false`). Finalmente, `return` devuelve ese resultado:
Cuando los métodos devuelven el resultado de una comparación, responden a la pregunta "sí" o "no". Esos métodos se llaman **predicados**. Se reconocen porque devuelven un valor lógico `true` o `false`. A menudo en el nombre de un predicado hay una pregunta o una afirmación que se puede comprobar (`is`, `has`, `can`, `was`). Aquí está un método que comprueba si un número es negativo:

```java
System.out.println(App.esBebe(3)); // => false
System.out.println(App.esBebe(0)); // => true
public static boolean isNegative(int number) {
// Comprobamos si el número es menor que cero
return number < 0;
}

System.out.println(App.isNegative(-5)); // => true
System.out.println(App.isNegative(7)); // => false
```

El método `isNegative` reúne la condición dentro y hacia fuera entrega una respuesta corta. Así el cálculo se esconde detrás de un nombre comprensible.
4 changes: 4 additions & 0 deletions modules/45-logic/10-bool-type/es/data.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
---
name: Tipo lógico
tips:
- >
[El tipo boolean en
Java](https://docs.oracle.com/javase/specs/jls/se21/html/jls-4.html#jls-4.2.5)
definitions:
- name: Tipo lógico (boolean)
description: >-
Expand Down
17 changes: 17 additions & 0 deletions modules/45-logic/12-string-comparasion/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

Implement the method `isPalindrome()`, which determines whether a word is a palindrome or not. A palindrome is a word that reads the same in both directions.

```java
App.isPalindrome("level"); // true
App.isPalindrome("wow"); // true
App.isPalindrome("hexlet"); // false

// Words can be passed to the method in any case
App.isPalindrome("Wow"); // true
```

To determine a palindrome, you need to reverse the string and compare it with the original one. Use the `StringUtils.reverse()` method for this

```java
StringUtils.reverse("mama"); // "amam"
```
122 changes: 122 additions & 0 deletions modules/45-logic/12-string-comparasion/en/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
Look at the code and try to answer what the values of these expressions are:

```java
// What will the result be in these examples — `true` or `false`?

"a" == "a";
"a".toUpperCase() == "a".toUpperCase();
```

The correct answer: in the first case `true`, in the second — `false`. Why? To answer this question you need to dive a little into how computers work.


In our programs we operate on data — numbers, strings, boolean values. We perform various operations — we store them in variables, multiply, divide, concatenate them.

That is how a programmer sees their work. But inside the computer everything is a bit different. While running, the program gets access to and manipulates data through their addresses in memory:

```java
// An area of memory is allocated for storing the variable
// The program remembers the address of this area and works with it internally
var name = "CodeBasics";
// The program read the value of the variable at the address where the value is stored
System.out.println(name);
```

**Memory** is a large area for storing data, which is very similar to a warehouse. In memory, any value gets a number by which it can be retrieved and replaced. This number is the **address**.

## Comparison by reference and by value

Because of these technical peculiarities, the comparison of data with each other can be looked at in two ways:

* *The same one* — the same piece of memory
* *The same kind* — identical values regardless of where the addresses point

An example from real life: two identical glasses from one set. Despite being identical, they are still different glasses.

Programming languages work with these notions differently. As in many other languages, in Java all data is divided into two large types:

* Primitive data is compared by value, regardless of addresses
* Reference data is compared by addresses

This is how primitive data works:

```java
// The comparison goes by value, not by addresses

Check notice on line 44 in modules/45-logic/12-string-comparasion/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/45-logic/12-string-comparasion/en/README.md#L44

Possible typo: you repeated a word (ENGLISH_WORD_REPEAT_RULE) Suggestions: `true` Rule: https://community.languagetool.org/rule/show/ENGLISH_WORD_REPEAT_RULE?lang=en-US Category: MISC
Raw output
modules/45-logic/12-string-comparasion/en/README.md:44:49: Possible typo: you repeated a word (ENGLISH_WORD_REPEAT_RULE)
 Suggestions: `true`
 Rule: https://community.languagetool.org/rule/show/ENGLISH_WORD_REPEAT_RULE?lang=en-US
 Category: MISC
4 == 4; // true
true == true; // true
10.0 == 10.0; // true
```

Of the reference data we are so far familiar only with strings, but they work in a tricky way, so as an example let's look at arrays. Do not pay attention to the unfamiliar syntax. Just note that in this code seemingly identical things are not equal to each other:

```java
// Creating arrays
int[] a = {1, 2}
int[] b = {1, 2}
// The values are identical, but the references are different
a == b; // false
```

## The peculiarities of strings

Strings belong to reference data types, but they behave strangely:

```java
// Comparison like with primitive data types
"hm" == "hm"; // true
// Comparison like with reference data types
"hexlet".toUpperCase() == "hexlet".toUpperCase(); // false
```

Programs constantly operate on strings, so the efficiency of working with them comes first. If a string always behaved like a reference type, then additional memory would be allocated for every value in the code:

```java
// Without optimizations this expression would lead to a double allocation of memory
// One unit of memory for each "hm"
"hm" == "hm";
```

But this does not happen. When Java meets an explicitly created string, a check is performed on whether such a string already exists in memory.

If it does, it is reused; if not, it is created:

```java
// Memory is allocated
var name1 = "Java";
// Such a string already exists, so a reference to the already created string is substituted
// As a result, memory is saved
var name2 = "Java";
// Comparison by reference
// Both variables point to one piece of memory
name1 == name2; // true
```

But if a string is returned from a method, then it is placed into its own area of memory with its own unique address:

```java
// New memory is allocated in any case
var name1 = "java".toUpperCase(); // "JAVA"
// New memory is allocated in any case
var name2 = "java".toUpperCase(); // "JAVA"
name1 == name2; // false
```

It may seem that reference data brings nothing but problems. In fact, it is needed. This will become clear when we come across mutability in the future.

In applied programming we compare strings by value more often than by reference. For this, the `equals()` method is built into strings:

```java
var name1 = "java".toUpperCase(); // "JAVA"
var name2 = "java".toUpperCase(); // "JAVA"
name1.equals(name2); // true
```

Besides `equals()`, the `equalsIgnoreCase()` method is built into strings, which performs a check by value without taking the case into account:

```java
var name1 = "java".toUpperCase(); // "JAVA"
var name2 = "java".toLowerCase(); // "java"
name1.equalsIgnoreCase(name2); // true
```

Sometimes comparing strings in Java behaves like comparing values, but never bet on that. When changing the code it is easy to forget to fix the check and get an error. Always use methods when you need to compare by value.
2 changes: 2 additions & 0 deletions modules/45-logic/12-string-comparasion/en/data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
name: Comparing strings
16 changes: 8 additions & 8 deletions modules/45-logic/12-string-comparasion/es/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@

Implementa el método `isPalindrome()`, que determina si una palabra es un palíndromo o no. Un palíndromo es una palabra que se lee igual en ambos sentidos.
Implementa el método `isPalindrome()`, que determina si una palabra es un palíndromo o no. Un palíndromo es una palabra que se lee igual en los dos sentidos.

```java
App.isPalindrome("шалаш"); // true
App.isPalindrome("ага"); // true
App.isPalindrome("хекслет"); // false
App.isPalindrome("reconocer"); // true
App.isPalindrome("ana"); // true
App.isPalindrome("hexlet"); // false

// Las palabras pueden estar en cualquier caso
App.isPalindrome("Ага"); // true
// Las palabras se pueden pasar al método en cualquier combinación de mayúsculas y minúsculas
App.isPalindrome("Ana"); // true
```

Para determinar si una palabra es un palíndromo, debes invertir la cadena y compararla con la original. Para esto, utiliza el método `StringUtils.reverse()`
Para determinar si una palabra es un palíndromo, hay que invertir la cadena y compararla con la original. Usa para eso el método `StringUtils.reverse()`

```java
StringUtils.reverse("мама"); // "амам"
StringUtils.reverse("mama"); // "amam"
```
7 changes: 7 additions & 0 deletions modules/45-logic/20-combine-expressions/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

Implement the method `isInternationalPhone()`, which checks the format of the given phone number. If the phone number starts with *+*, then it is the international format.

```java
App.isInternationalPhone("89602223423"); // false
App.isInternationalPhone("+79602223423"); // true
```
Loading
Loading