diff --git a/modules/33-data-types/41-data-types-basics/en/EXERCISE.md b/modules/33-data-types/41-data-types-basics/en/EXERCISE.md index a4eaba0..8b23e58 100644 --- a/modules/33-data-types/41-data-types-basics/en/EXERCISE.md +++ b/modules/33-data-types/41-data-types-basics/en/EXERCISE.md @@ -1 +1 @@ -Display the number `-0.304`. +Display on the screen the result of dividing the integers 3 by 2. Think about why the answer turned out this way? diff --git a/modules/33-data-types/41-data-types-basics/en/README.md b/modules/33-data-types/41-data-types-basics/en/README.md index 32b8c7a..ba0812a 100644 --- a/modules/33-data-types/41-data-types-basics/en/README.md +++ b/modules/33-data-types/41-data-types-basics/en/README.md @@ -1,62 +1,44 @@ +Programs work with different information. This can be text, numbers, dates, boolean values. Inside high-level programming languages, every value belongs to some type. For example, strings belong to the type *String*, and integers belong to the type *int*. -Data types in Java are divided into two important groups according to how variables of this type are related and the values stored in them. +Why are types needed? They protect the program from hard-to-catch errors. A type defines two things. -What will the following code output? +* Allowed values. For example, numbers in Java are divided into two groups. Integers belong to the type *int*, and rational (fractional) numbers to the type *double*. This division is related to the specifics of how the hardware works. +* A set of allowed operations. For example, the multiplication operation makes sense for integers. But it does not make sense for strings. Multiplying the word "mother" by the word "notepad" is nonsense. -```java -var a = 10; -var b = a; -a = 20; -System.out.print(b); -``` - -10 will be output, because with the assignment b = a, the number 10, which at this moment is contained in a, will be written into the variable b. - -If you write +A programming language recognizes types. That is why Java will not allow multiplying a string by a string, but will allow multiplying an integer by another integer. The presence of types and such restrictions protects programs from accidental errors: -```java -var a = "string"; -var b = a; +```text +"one" * "two" +Error: +bad operand types for binary operator '*' + first type: java.lang.String + second type: java.lang.String ``` -- then the situation will be different. - -#### Briefly - -Primitive data types in Java: - -- Strings in quotes -- The numbers `7`,` -198`, `0` and so on +## Numbers and strings belong to different types -In fact, there are more, but now let's talk only about them. ---- - -There are different ways to present data in programs. - -There are **strings** - character sets in quotes like `"Hello, World!"`. There are **integers** - for example, `7`, `-198`, `0`. These are two different categories of information - two different **data types**. - -The multiplication operation makes sense for integers but it does not make sense for strings: to multiply the word "mother" by the word "notepad" is nonsense. - -**The data type determines what can be done with the elements of a specific set of information.** - -A programming language recognizes types. Therefore, Java will not allow us to multiply a line by line (“multiply text by text”). But it will allow to multiply an integer by another integer. The presence of types and such restrictions in the language protects programs from random errors. - -Unlike strings, numbers do not need to be wrapped in quotes. To print the number 5, just write: +How does Java understand what type of data it is dealing with? By the way the value is written. A number is written without quotes, while strings are always enclosed in double quotes. For example, the value `"234"` is considered a string, even though digits are written inside it: ```java -System.out.print(5); +System.out.println(5); // => 5 +System.out.println("234"); // => 234 ``` -Note that the number `5` and the string `"5"` are completely different things, although the output of `println` for this data is identical. +On the screen the result looks similar, but inside the program these are different values. The number `5` belongs to the type *int*, and `"234"` to the type *String*. Java will not let you add a string and a number directly without an explicit indication of how to convert the data. -Integers (`1`, `34`, `-19`, etc.) and rational numbers (`1.3`, `1.0`, `-14.324`, etc.) are two separate **types data**. This separation is associated with the characteristics of the device computers. **There are other types**, we will get to know them later. +## Primitive and reference types -Here is another example, but with a rational number: +Some types are built into the language. They are called primitive. Besides integers *int* and rational numbers *double*, they include the boolean type *boolean* with the values `true` and `false`, as well as the character type *char*: ```java -System.out.print(10.234); +int n = 5; // integer +double x = 1.5; // rational number +boolean flag = true; // boolean value +char c = 'A'; // one character ``` -The lines in programming are called "strings", and the lines of text files are called "lines". For example, the code above has one line (lines), and there are no lines (strings). In all the lessons we will say **string** to indicate the data type "string", and **line** to indicate lines (lines) in files). +Pay attention to the type *char*. A character is written in single quotes, for example `'A'`. But a string of one character is enclosed in double quotes, for example `"A"`. These are different values of different types. + +The type *String* belongs to reference types and describes a set of characters, that is, text. At the same time, strings are used on par with primitive types. -Programmers themselves can create new data types, albeit with certain restrictions. +There are many data types in Java, plus you can create your own. Gradually we will get to know all the necessary ones and learn to use them correctly. diff --git a/modules/33-data-types/41-data-types-basics/en/data.yml b/modules/33-data-types/41-data-types-basics/en/data.yml index bdcf8b5..936145b 100644 --- a/modules/33-data-types/41-data-types-basics/en/data.yml +++ b/modules/33-data-types/41-data-types-basics/en/data.yml @@ -1,5 +1,19 @@ --- -name: Data Types +name: Why data types are needed tips: + - > + [Literal](https://en.wikipedia.org/wiki/Literal_(computer_programming)) - | [Article on fractional numbers](https://habrahabr.ru/post/112953/) +definitions: + - name: Data type + description: >- + a set of data in code (a kind of information). A type defines what + can be done with the elements of a particular set. For example, integers, + rational numbers, and strings are different data types. + - name: Primitive data types + description: basic types built into the programming language itself. + - name: String + description: > + a data type that describes a set of characters (in other words, text), for + example `"text"`. In Java, strings are written in double quotes. diff --git a/modules/33-data-types/41-data-types-basics/es/EXERCISE.md b/modules/33-data-types/41-data-types-basics/es/EXERCISE.md index 648b623..1cf9b40 100644 --- a/modules/33-data-types/41-data-types-basics/es/EXERCISE.md +++ b/modules/33-data-types/41-data-types-basics/es/EXERCISE.md @@ -1 +1 @@ -Muestra en pantalla el resultado de dividir los números enteros 3 entre 2. ¿Por qué se obtuvo ese resultado? +Muestra en pantalla el resultado de dividir los números enteros 3 entre 2. Piensa por qué se obtuvo esa respuesta. diff --git a/modules/33-data-types/41-data-types-basics/es/README.md b/modules/33-data-types/41-data-types-basics/es/README.md index c73f104..7d99575 100644 --- a/modules/33-data-types/41-data-types-basics/es/README.md +++ b/modules/33-data-types/41-data-types-basics/es/README.md @@ -1,32 +1,44 @@ -Dentro de los lenguajes de programación de alto nivel, los datos se dividen en tipos. Por ejemplo, las cadenas de texto se clasifican como *String*, mientras que los números se clasifican como *int*. +Los programas trabajan con información diferente. Puede ser texto, números, fechas, valores lógicos. Dentro de los lenguajes de programación de alto nivel, cada valor pertenece a algún tipo. Por ejemplo, las cadenas pertenecen al tipo *String*, y los números enteros al tipo *int*. -¿Para qué sirven los tipos de datos? Para proteger el programa de errores difíciles de detectar. Los tipos de datos determinan dos cosas: +¿Para qué sirven los tipos? Protegen el programa de errores difíciles de detectar. Un tipo define dos cosas. -* Valores permitidos. Por ejemplo, en Java, los números se dividen en dos grupos de tipos: enteros (*int*) y racionales (*float*). Esta división está relacionada con las características técnicas del hardware. -* Conjunto de operaciones permitidas. Por ejemplo, la operación de multiplicación tiene sentido para el tipo "números enteros". Pero no tiene sentido para el tipo "cadena de texto": multiplicar la palabra "mamá" por la palabra "cuaderno" no tiene sentido. +* Valores permitidos. Por ejemplo, los números en Java se dividen en dos grupos. Los números enteros pertenecen al tipo *int*, y los racionales (decimales) al tipo *double*. Esta división está relacionada con las particularidades del funcionamiento del hardware. +* Un conjunto de operaciones permitidas. Por ejemplo, la operación de multiplicación tiene sentido para los números enteros. Pero no tiene sentido para las cadenas. Multiplicar la palabra "mamá" por la palabra "cuaderno" es un sinsentido. -El lenguaje de programación reconoce los tipos. Por lo tanto, Java no nos permitirá multiplicar una cadena de texto por otra cadena de texto. Pero sí nos permitirá multiplicar un número entero por otro número entero. La presencia de tipos y de tales restricciones en el lenguaje protege los programas de errores accidentales: +El lenguaje de programación reconoce los tipos. Por eso Java no permitirá multiplicar una cadena por una cadena, pero sí permitirá multiplicar un número entero por otro número entero. La presencia de tipos y de tales restricciones protege los programas de errores accidentales: ```text -"uno" * "dos" +"one" * "two" Error: -tipos de operandos incorrectos para el operador binario '*' - primer tipo: java.lang.String - segundo tipo: java.lang.String +bad operand types for binary operator '*' + first type: java.lang.String + second type: java.lang.String ``` -¿Cómo sabe Java qué tipo de datos tiene delante? Cada valor se inicializa en algún lugar. Dependiendo de la forma de inicialización, se entiende qué es exactamente lo que tenemos delante. +## Los números y las cadenas pertenecen a tipos diferentes -Por ejemplo, un número es simplemente un número, no está envuelto entre comillas u otros caracteres emparejados. Pero las cadenas de texto siempre están delimitadas por comillas dobles. Por ejemplo, el valor `"234"` se considera una cadena de texto, aunque dentro de ella se escriban números: +¿Cómo entiende Java qué tipo de datos tiene delante? Por la forma en que se escribe el valor. Un número se escribe sin comillas, mientras que las cadenas siempre están delimitadas por comillas dobles. Por ejemplo, el valor `"234"` se considera una cadena, aunque dentro estén escritos dígitos: ```java -// El compilador entiende que aquí hay un número -var edad = 33; +System.out.println(5); // => 5 +System.out.println("234"); // => 234 ``` -En inglés, las cadenas de texto en programación se llaman *strings*, mientras que las líneas de los archivos de texto se llaman *lines*. Por ejemplo, en el código anterior hay una línea (*line*) y cero cadenas (*strings*). En el idioma ruso, a veces puede haber confusión, por lo tanto, en todas las lecciones utilizaremos los siguientes términos: +En la pantalla el resultado se ve parecido, pero dentro del programa son valores diferentes. El número `5` pertenece al tipo *int*, y `"234"` al tipo *String*. Java no te dejará sumar una cadena y un número directamente sin una indicación explícita de cómo convertir los datos. -* **Cadena de texto** - para denotar el tipo de datos *strings* -* **Línea** - para denotar *lines* (líneas en archivos de texto) +## Tipos primitivos y de referencia -Hay muchos tipos de datos en Java, y también se pueden crear tipos personalizados. Gradualmente nos familiarizaremos con todos los necesarios y aprenderemos a usarlos correctamente. +Una parte de los tipos está integrada en el lenguaje. Se les llama primitivos. Además de los números enteros *int* y los racionales *double*, incluyen el tipo lógico *boolean* con los valores `true` y `false`, así como el carácter *char*: + +```java +int n = 5; // número entero +double x = 1.5; // número racional +boolean flag = true; // valor lógico +char c = 'A'; // un carácter +``` + +Presta atención al tipo *char*. Un carácter se escribe entre comillas simples, por ejemplo `'A'`. En cambio, una cadena de un solo carácter se encierra entre comillas dobles, por ejemplo `"A"`. Son valores diferentes de tipos diferentes. + +El tipo *String* pertenece a los tipos de referencia y describe un conjunto de caracteres, es decir, texto. Al mismo tiempo, las cadenas se usan al mismo nivel que los tipos primitivos. + +Hay muchos tipos de datos en Java, y además se pueden crear los propios. Poco a poco nos familiarizaremos con todos los necesarios y aprenderemos a usarlos correctamente. diff --git a/modules/33-data-types/41-data-types-basics/es/data.yml b/modules/33-data-types/41-data-types-basics/es/data.yml index f8a1985..f5afcc3 100644 --- a/modules/33-data-types/41-data-types-basics/es/data.yml +++ b/modules/33-data-types/41-data-types-basics/es/data.yml @@ -1,5 +1,21 @@ --- name: ¿Para qué sirven los tipos de datos? tips: + - > + [Literal](https://es.wikipedia.org/wiki/Constante_(inform%C3%A1tica)) - | [Artículo sobre números decimales](https://habrahabr.ru/post/112953/) +definitions: + - name: Tipo de datos + description: >- + un conjunto de datos en el código (una variedad de información). El tipo + define qué se puede hacer con los elementos de un conjunto concreto. Por + ejemplo, los números enteros, los números racionales y las cadenas son + tipos de datos diferentes. + - name: Tipos de datos primitivos + description: tipos básicos integrados en el propio lenguaje de programación. + - name: Cadena (string) + description: > + tipo de datos que describe un conjunto de caracteres (en otras palabras, + texto), por ejemplo `"text"`. En Java, las cadenas se escriben entre + comillas dobles. diff --git a/modules/33-data-types/45-explicit-types/en/EXERCISE.md b/modules/33-data-types/45-explicit-types/en/EXERCISE.md index a4eaba0..a2c3bc2 100644 --- a/modules/33-data-types/45-explicit-types/en/EXERCISE.md +++ b/modules/33-data-types/45-explicit-types/en/EXERCISE.md @@ -1 +1 @@ -Display the number `-0.304`. +Create the string *One more time* with an explicit type specification and print it to the screen. diff --git a/modules/33-data-types/45-explicit-types/en/README.md b/modules/33-data-types/45-explicit-types/en/README.md index 32b8c7a..58b7e39 100644 --- a/modules/33-data-types/45-explicit-types/en/README.md +++ b/modules/33-data-types/45-explicit-types/en/README.md @@ -1,62 +1,62 @@ - -Data types in Java are divided into two important groups according to how variables of this type are related and the values stored in them. - -What will the following code output? +Until now, when defining variables, we used the keyword `var`. This may surprise those who already have experience with Java. Usually the definition of variables is shown like this: ```java -var a = 10; -var b = a; -a = 20; -System.out.print(b); +int x = 3; +String greeting = "Hello Hexlet!"; ``` -10 will be output, because with the assignment b = a, the number 10, which at this moment is contained in a, will be written into the variable b. +The time has come to reveal the cards. Java is a statically typed language. In such languages, the type of a variable is fixed at its declaration and does not change until the end of the program. The type is specified before the variable name. In the example above, this is an integer (*int*) and a string (*String*). + +## The type is specified explicitly and does not change -If you write +In a statically typed language, every variable has a type, and it is fixed. If a variable is declared as *int*, then only an integer can be put into it: ```java -var a = "string"; -var b = a; +int n = 5; +double x = 1.5; +boolean flag = true; +char c = 'A'; +String s = "hi"; ``` -- then the situation will be different. - -#### Briefly - -Primitive data types in Java: +An attempt to put a value of another type into a variable leads to an error. A string cannot be assigned to a variable of type *int*: -- Strings in quotes -- The numbers `7`,` -198`, `0` and so on - -In fact, there are more, but now let's talk only about them. ---- +```java +// Error: incompatible types: java.lang.String cannot be converted to int +int ops = "test"; +``` -There are different ways to present data in programs. +## When types are checked -There are **strings** - character sets in quotes like `"Hello, World!"`. There are **integers** - for example, `7`, `-198`, `0`. These are two different categories of information - two different **data types**. +Java checks types in advance, even before the program runs, at the compilation stage. The compiler reads the code, checks the types of values and operations, and refuses to build the program if it finds a mismatch. That is why we will see the error from the example above before the program starts working. -The multiplication operation makes sense for integers but it does not make sense for strings: to multiply the word "mother" by the word "notepad" is nonsense. +In this, Java differs from languages with dynamic typing, where types are checked while the program is running. In such languages, a type mismatch error surfaces only at the moment the appropriate line of code executes. Static checking catches some errors earlier and helps not to carry them all the way to the user. -**The data type determines what can be done with the elements of a specific set of information.** +Explicit type specification has a second advantage as well. The type next to the variable name works as a hint for whoever reads the code. From the line `int count = 0;` it is immediately clear that the variable stores an integer. Java takes control of types upon itself, and the code becomes clearer for people. -A programming language recognizes types. Therefore, Java will not allow us to multiply a line by line (“multiply text by text”). But it will allow to multiply an integer by another integer. The presence of types and such restrictions in the language protects programs from random errors. +## When Java casts types itself -Unlike strings, numbers do not need to be wrapped in quotes. To print the number 5, just write: +Sometimes values of different numeric types appear in one expression. If you add an integer and a rational number, Java itself casts the integer to a rational one: ```java -System.out.print(5); +double result = 1 + 1.5; +System.out.println(result); // => 2.5 ``` -Note that the number `5` and the string `"5"` are completely different things, although the output of `println` for this data is identical. +The integer `1` turns into `1.0`, and the result comes out as `2.5`. This happens because any integer can be represented exactly as a rational number, and no data is lost. But Java will not mix a string and a number by itself. For that, an explicit conversion is needed, and we will learn to do it. -Integers (`1`, `34`, `-19`, etc.) and rational numbers (`1.3`, `1.0`, `-14.324`, etc.) are two separate **types data**. This separation is associated with the characteristics of the device computers. **There are other types**, we will get to know them later. +## Type inference and the word var -Here is another example, but with a rational number: +Earlier in Java variables were created only with an explicit type specification, until the word `var` appeared. This is a special keyword that turns on the mechanism of **type inference**. Type inference itself determines the type of the assigned value and binds it to the variable: ```java -System.out.print(10.234); +// The compiler understands that this is an integer +var age = 33; + +// And this is a string +var name = "Tom"; ``` -The lines in programming are called "strings", and the lines of text files are called "lines". For example, the code above has one line (lines), and there are no lines (strings). In all the lessons we will say **string** to indicate the data type "string", and **line** to indicate lines (lines) in files). +Type inference appeared in Java in 2018, although in some other languages it has existed for several decades. The first language with type inference is called ML, and it appeared as early as 1973. Since then, type inference has been added to OCaml, Haskell, C#, F#, Kotlin, Scala, and many other languages. -Programmers themselves can create new data types, albeit with certain restrictions. +The word `var` does not cancel static typing. The variable still has a type; the compiler infers it. After that the type is just as fixed, and you will not be able to put a value of another type into such a variable. Type inference is preferable in most situations. It happens that the inferred type does not suit us, and then the type is specified explicitly. diff --git a/modules/33-data-types/45-explicit-types/en/data.yml b/modules/33-data-types/45-explicit-types/en/data.yml index bdcf8b5..70dd99a 100644 --- a/modules/33-data-types/45-explicit-types/en/data.yml +++ b/modules/33-data-types/45-explicit-types/en/data.yml @@ -1,5 +1,16 @@ --- -name: Data Types +name: Explicit typing tips: + - | + [Typing](https://en.wikipedia.org/wiki/Strong_and_weak_typing) - | [Article on fractional numbers](https://habrahabr.ru/post/112953/) +definitions: + - name: Static typing + description: >- + an approach in which the type of a variable is fixed at its declaration and + is checked in advance, at the compilation stage, before the program runs. + - name: Type inference + description: >- + a mechanism that itself determines the type of the assigned value and binds + it to the variable. In Java it is turned on with the keyword `var`. diff --git a/modules/33-data-types/45-explicit-types/es/EXERCISE.md b/modules/33-data-types/45-explicit-types/es/EXERCISE.md index 1756b09..7efc44e 100644 --- a/modules/33-data-types/45-explicit-types/es/EXERCISE.md +++ b/modules/33-data-types/45-explicit-types/es/EXERCISE.md @@ -1 +1 @@ -Crea una cadena de texto *One more time* con una especificación explícita de tipo y muéstrala en pantalla. +Crea la cadena *One more time* con una indicación explícita del tipo y muéstrala en pantalla. diff --git a/modules/33-data-types/45-explicit-types/es/README.md b/modules/33-data-types/45-explicit-types/es/README.md index 59552b1..de021de 100644 --- a/modules/33-data-types/45-explicit-types/es/README.md +++ b/modules/33-data-types/45-explicit-types/es/README.md @@ -1,17 +1,62 @@ -Hasta ahora, al definir variables, hemos utilizado la palabra clave `var`, lo cual puede sorprender a aquellos que tienen experiencia en Java. Normalmente, la definición de variables se muestra así: +Hasta ahora, al definir variables, hemos usado la palabra clave `var`. Esto puede sorprender a quienes ya tienen experiencia con Java. Normalmente, la definición de variables se muestra así: ```java int x = 3; -String greeting = "¡Hola Hexlet!"; +String greeting = "Hello Hexlet!"; +``` + +Ha llegado el momento de descubrir las cartas. Java es un lenguaje de tipado estático. En estos lenguajes, el tipo de una variable se fija en su declaración y no cambia hasta el final del programa. El tipo se indica antes del nombre de la variable. En el ejemplo anterior, se trata de un número entero (*int*) y una cadena (*String*). + +## El tipo se indica explícitamente y no cambia + +En un lenguaje de tipado estático, cada variable tiene un tipo, y este está fijado. Si una variable se declara como *int*, entonces solo se puede poner en ella un número entero: + +```java +int n = 5; +double x = 1.5; +boolean flag = true; +char c = 'A'; +String s = "hi"; +``` + +Un intento de poner en una variable un valor de otro tipo provoca un error. Una cadena no se puede asignar a una variable de tipo *int*: -// Error: tipos incompatibles: java.lang.String no se puede convertir a int +```java +// Error: incompatible types: java.lang.String cannot be converted to int int ops = "test"; ``` -¡Es hora de revelar la verdad! Java es un lenguaje de programación de tipado estático. En estos lenguajes, el tipo de una variable se establece al momento de su declaración. En la mayoría de los lenguajes, se especifica el tipo de la variable antes de su nombre, como en el ejemplo anterior, donde se utiliza el tipo entero (int) y el tipo cadena (String). +## Cuándo se comprueban los tipos + +Java comprueba los tipos de antemano, aún antes de ejecutar el programa, en la etapa de compilación. El compilador lee el código, coteja los tipos de los valores y las operaciones, y se niega a construir el programa si encuentra una incongruencia. Por eso veremos el error del ejemplo anterior antes de que el programa empiece a funcionar. + +En esto Java se diferencia de los lenguajes con tipado dinámico, donde los tipos se comprueban durante la ejecución del programa. En estos lenguajes, el error de incongruencia de tipos aparece solo en el momento en que se ejecuta la línea de código correspondiente. La comprobación estática detecta parte de los errores antes y ayuda a no arrastrarlos hasta el usuario. + +La indicación explícita de tipos tiene también una segunda ventaja. El tipo junto al nombre de la variable funciona como una pista para quien lee el código. Por la línea `int count = 0;` se ve enseguida que la variable almacena un número entero. Java asume el control de los tipos, y el código se vuelve más claro para las personas. -Antes en Java, las variables solo se creaban de esta manera, hasta que apareció `var`. La palabra clave `var` es una característica especial que habilita la **inferencia de tipos**. La inferencia de tipos determina automáticamente el tipo del valor asignado y lo vincula a la variable. En los ejemplos anteriores, es obvio qué tipo corresponde a cada variable, entonces, ¿por qué especificarlo explícitamente? +## Cuándo Java convierte los tipos por sí misma + +A veces, en una misma expresión aparecen valores de tipos numéricos diferentes. Si sumas un número entero y uno racional, Java convierte por sí misma el entero en racional: + +```java +double result = 1 + 1.5; +System.out.println(result); // => 2.5 +``` + +El entero `1` se convierte en `1.0`, y el resultado sale `2.5`. Esto ocurre porque cualquier número entero se puede representar con exactitud como número racional, y no se pierden datos. En cambio, Java no mezclará por sí misma una cadena y un número. Para eso se necesita una conversión explícita, y aprenderemos a hacerla. + +## La inferencia de tipos y la palabra var + +Antes en Java las variables se creaban solo con una indicación explícita del tipo, hasta que apareció la palabra `var`. Es una palabra clave especial que activa el mecanismo de **inferencia de tipos**. La inferencia de tipos determina por sí misma el tipo del valor asignado y lo vincula a la variable: + +```java +// El compilador entiende que aquí hay un número entero +var age = 33; + +// Y aquí hay una cadena +var name = "Tom"; +``` -La inferencia de tipos en Java se introdujo en 2018, pero en otros lenguajes ha existido durante décadas. El primer lenguaje con inferencia de tipos se llama ML y se creó en 1973. Desde entonces, la inferencia de tipos se ha agregado a Ocaml, Haskell, C#, F#, Kotlin, Scala y muchos otros lenguajes. +La inferencia de tipos apareció en Java en 2018, aunque en algunos otros lenguajes existe desde hace varias décadas. El primer lenguaje con inferencia de tipos se llama ML, y apareció ya en 1973. Desde entonces, la inferencia de tipos se ha añadido a OCaml, Haskell, C#, F#, Kotlin, Scala y muchos otros lenguajes. -La inferencia de tipos es preferible en la mayoría de las situaciones, sin embargo, a veces no estamos satisfechos con el tipo inferido. En ese caso, podemos especificar el tipo explícitamente. Obtendrás más información al respecto en la próxima lección. +La palabra `var` no anula el tipado estático. La variable sigue teniendo un tipo; lo infiere el compilador. Después de eso el tipo queda igualmente fijado, y no podrás poner en esa variable un valor de otro tipo. La inferencia de tipos es preferible en la mayoría de las situaciones. Sucede que el tipo inferido no nos conviene, y entonces el tipo se indica explícitamente. diff --git a/modules/33-data-types/45-explicit-types/es/data.yml b/modules/33-data-types/45-explicit-types/es/data.yml index 19e6974..b7f7baf 100644 --- a/modules/33-data-types/45-explicit-types/es/data.yml +++ b/modules/33-data-types/45-explicit-types/es/data.yml @@ -1,5 +1,17 @@ --- name: Tipado explícito tips: + - | + [Tipado](https://es.wikipedia.org/wiki/Tipado_fuerte) - | [Artículo sobre números decimales](https://habrahabr.ru/post/112953/) +definitions: + - name: Tipado estático + description: >- + un enfoque en el que el tipo de una variable se fija en su declaración y se + comprueba de antemano, en la etapa de compilación, aún antes de ejecutar el + programa. + - name: Inferencia de tipos (type inference) + description: >- + un mecanismo que determina por sí mismo el tipo del valor asignado y lo + vincula a la variable. En Java se activa con la palabra clave `var`. diff --git a/modules/33-data-types/55-type-casting/en/EXERCISE.md b/modules/33-data-types/55-type-casting/en/EXERCISE.md index a9b8ea5..fb26d88 100644 --- a/modules/33-data-types/55-type-casting/en/EXERCISE.md +++ b/modules/33-data-types/55-type-casting/en/EXERCISE.md @@ -1 +1,5 @@ -Display the string `2 times`, obtained from the number 2.9 and the string `times`, using type conversions and concatenation. + +Display on the screen the string `2 times`, obtained from the number 2.9 and the string `times`, using type conversions and concatenation. +```text +2 times +``` diff --git a/modules/33-data-types/55-type-casting/en/README.md b/modules/33-data-types/55-type-casting/en/README.md index ca72d04..f28f14e 100644 --- a/modules/33-data-types/55-type-casting/en/README.md +++ b/modules/33-data-types/55-type-casting/en/README.md @@ -1,19 +1,43 @@ +In real programs, a situation often arises when data of one type needs to be turned into another. One example is working with forms on websites. Form data comes in text form, even if by its meaning there is a number there. To do something with such a value, it is converted into the needed type. -Java is a strongly typed programming language. Using special syntax we can change type of variables: +## Converting a string to a number + +Let's imagine that a string `"345"` came from a form, and we need to add another number to this number. The string is first turned into an integer: + +```java +var number = Integer.parseInt("345"); +System.out.println(number + 5); // => 350 +``` + +The method `Integer.parseInt` takes a string and returns an integer of type *int*. In a similar way, a string is turned into a rational number using `Double.parseDouble`. + +## Casting between primitive types + +If you need to convert from one primitive type to another, it is enough to specify the type in parentheses before the value. The value is converted to the type written in parentheses: ```java -System.out.print(Integer.parseInt("345")); +var result = (int) 5.1; +System.out.println(result); // => 5 ``` -Type conversion works like this: before the value, the desired type is indicated in parentheses. As a result, the value on the right is converted to a value of another type indicated on the left in parentheses. At the moment we are familiar with only two types, but the transformation in Java works not only for the primitive types. +When casting a rational number to an integer, the fractional part is discarded without rounding. That is why `(int) 5.9` gives `5`. In the opposite direction, `(double) 7` gives `7.0`. -Type conversion can be used inside compound expressions: +Casting also helps with division. Dividing an integer by an integer in Java gives an integer, and the fractional part is lost: ```java -//Additional brackets help to visually separate parts of the expression from each other -System.out.print("It's" + ((int) 5.1)); +System.out.println(7 / 2); // => 3 +System.out.println((double) 7 / 2); // => 3.5 ``` -It's 5 +In the first case both values are integers, so the result is an integer. In the second case the dividend is cast to the type *double*, and the division became rational. + +## Casting inside compound expressions + +Type conversion also works inside large expressions. Additional parentheses help to visually separate the parts of the expression from each other: + +```java +var result = 10 + ((int) 5.1); +System.out.println(result); // => 15 +``` -In case above, in spite of the fact, that 5.1 is the number, it has double type not int. Expression above bring this number type to int type, reject fraction part, because int type doesn't keep fraction part. +Here `5.1` is cast to `5`, and then added to `10`. diff --git a/modules/33-data-types/55-type-casting/en/data.yml b/modules/33-data-types/55-type-casting/en/data.yml index c1e1a4e..c6031d2 100644 --- a/modules/33-data-types/55-type-casting/en/data.yml +++ b/modules/33-data-types/55-type-casting/en/data.yml @@ -1,2 +1,10 @@ --- name: Explicit type conversion +tips: + - | + [Typing](https://en.wikipedia.org/wiki/Strong_and_weak_typing) +definitions: + - name: Type casting + description: >- + the explicit conversion of a value of one type into a value of another type. + For example, `(int) 5.1` casts a rational number to an integer. diff --git a/modules/33-data-types/55-type-casting/es/EXERCISE.md b/modules/33-data-types/55-type-casting/es/EXERCISE.md index b4edc24..f44eefa 100644 --- a/modules/33-data-types/55-type-casting/es/EXERCISE.md +++ b/modules/33-data-types/55-type-casting/es/EXERCISE.md @@ -1,5 +1,5 @@ -Imprime en la pantalla la cadena de texto `2 times`, obtenida a partir del número 2.9 y la cadena de texto `times`, utilizando conversiones de tipos y concatenación. +Muestra en pantalla la cadena `2 times`, obtenida a partir del número 2.9 y la cadena `times`, usando conversiones de tipos y concatenación. ```text 2 times ``` diff --git a/modules/33-data-types/55-type-casting/es/README.md b/modules/33-data-types/55-type-casting/es/README.md index 96f906d..6d6cd60 100644 --- a/modules/33-data-types/55-type-casting/es/README.md +++ b/modules/33-data-types/55-type-casting/es/README.md @@ -1,24 +1,43 @@ -En programación, a menudo nos encontramos con situaciones en las que es necesario convertir un tipo de datos en otro. Un ejemplo sencillo es trabajar con formularios en sitios web. +En los programas reales, a menudo surge una situación en la que hay que convertir datos de un tipo en otro. Un ejemplo es el trabajo con formularios en los sitios web. Los datos del formulario llegan en formato de texto, incluso si por su significado allí hay un número. Para operar con ese valor, se convierte al tipo necesario. -Los datos de los formularios siempre llegan en formato de texto, incluso si el valor es un número. Así es cómo se puede convertir: +## Conversión de una cadena en número + +Imaginemos que del formulario llegó la cadena `"345"`, y necesitamos sumar a este número otro. Primero se convierte la cadena en un número entero: ```java -// se convierte en int var number = Integer.parseInt("345"); -System.out.println(number); // => 345 +System.out.println(number + 5); // => 350 ``` -Si necesitas convertir de un tipo primitivo a otro tipo primitivo, es más sencillo. Solo necesitas especificar el tipo deseado entre paréntesis antes del valor. Como resultado, el valor se convertirá en el valor de otro tipo especificado entre paréntesis: +El método `Integer.parseInt` recibe una cadena y devuelve un número entero de tipo *int*. De forma parecida se convierte una cadena en un número racional con `Double.parseDouble`. + +## Conversión entre tipos primitivos + +Si hay que convertir de un tipo primitivo a otro, basta con indicar el tipo entre paréntesis antes del valor. El valor se convierte al tipo escrito entre paréntesis: ```java var result = (int) 5.1; System.out.println(result); // => 5 ``` -La conversión de tipos se puede utilizar dentro de expresiones compuestas: +Al convertir un número racional en entero, la parte decimal se descarta sin redondear. Por eso `(int) 5.9` da `5`. En sentido inverso, `(double) 7` da `7.0`. + +La conversión también ayuda en la división. Dividir un entero entre un entero en Java da un número entero, y la parte decimal se pierde: + +```java +System.out.println(7 / 2); // => 3 +System.out.println((double) 7 / 2); // => 3.5 +``` + +En el primer caso ambos valores son enteros, por eso el resultado es entero. En el segundo caso el dividendo está convertido al tipo *double*, y la división pasó a ser racional. + +## Conversión dentro de expresiones compuestas + +La conversión de tipos también funciona dentro de expresiones grandes. Los paréntesis adicionales ayudan a separar visualmente unas partes de la expresión de otras: ```java -// Los paréntesis adicionales ayudan a separar visualmente las partes de la expresión var result = 10 + ((int) 5.1); System.out.println(result); // => 15 ``` + +Aquí `5.1` se convierte en `5`, y luego se suma con `10`. diff --git a/modules/33-data-types/55-type-casting/es/data.yml b/modules/33-data-types/55-type-casting/es/data.yml index 9fb73bc..da21dc3 100644 --- a/modules/33-data-types/55-type-casting/es/data.yml +++ b/modules/33-data-types/55-type-casting/es/data.yml @@ -1,2 +1,10 @@ --- name: Conversión explícita de tipos +tips: + - | + [Tipado](https://es.wikipedia.org/wiki/Tipado_fuerte) +definitions: + - name: Conversión de tipos (casting) + description: >- + la conversión explícita de un valor de un tipo en un valor de otro tipo. + Por ejemplo, `(int) 5.1` convierte un número racional en entero. diff --git a/modules/33-data-types/description.en.yml b/modules/33-data-types/description.en.yml index e3139af..7cd7d10 100644 --- a/modules/33-data-types/description.en.yml +++ b/modules/33-data-types/description.en.yml @@ -1,5 +1,5 @@ --- -name: Data Types +name: Data Types in Java description: | -  Java is a strongly typed language with different data types. You will find out what this means in the current module. + Java is a language with strict static typing. How this affects the code, what types are, what kinds there are, and who infers them. All this is studied in this module.