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
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

Implement a static method named `printMotto()` that prints the phrase *Winter is coming* to the screen.

```java
// The App class is already defined
App.printMotto(); // => Winter is coming
```

So that we can call this method from outside, it has to be marked not only with the `static` keyword, but also with `public`.

In exercises where you need to implement a method, you do not need to call that method. The method will be called by the automated tests that check whether it works. The example with the call above is shown only so that you understand how your method will be used.
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
Defining your own methods makes writing and maintaining programs much easier. For example, methods let you combine compound operations into one.

Sending an email from a site is a complex process that includes interaction with the internet. You can define a method and hide all that complexity behind one short construct:

```java
// The place the method comes from
import com.example.Mailer;

var email = "support@hexlet.io";
var title = "Help";
var body = "I have written a success story, how can I get a discount?";

// Mailer is the name of the class in which the send() method is defined
// One small call — and a lot of logic inside
Mailer.send(email, title, body);
```

Inside, a call like this performs quite a lot of logic. It connects to the mail server, forms the correct request based on the subject and the body of the message, and then sends it all, without forgetting to close the connection.

## How to create methods

Let's create our first method. Its task is to print the current date to the screen:

```text
Today is: 2021-10-25
```

```java
import java.time.LocalDate;

// Defining the method
// The definition does not call or execute the method
// We only say that such a method now exists
public class App {
public static void showCurrentDate() {
// A built-in Java method for getting the current time and date
var currentDate = LocalDate.now();
var text = "Today is: " + currentDate;
System.out.println(text);
}
}

// Calling the method
// Specifying the class name is required
App.showCurrentDate(); // => Today is: 2021-10-25
```

Let's look at the method signature part by part:

```text
public static void showCurrentDate()
│ │ │ │
│ │ │ the method name and the list of parameters in parentheses
│ │ the type of the returned value
│ static — the method is called directly from the class
the visibility of the method outside the class
```

Defining a method in Java includes many things that we will cover step by step.

They can be divided into two groups:

* What affects the work of the method itself
* How this method is visible outside the class

Visibility is handled by the word *public*. It makes it possible to call methods from outside the class, as in the example above. Besides it, there is *private*, which is covered at Hexlet in the [Java OOP](https://ru.hexlet.io/programs/java?utm_source=code-basics&utm_medium=referral&utm_campaign=programs&utm_content=lesson) course.

The work of the method is handled by:

* *static* — detaches the method from an object and makes it possible to call it directly from the class
* *void* is used if the method returns nothing. For example, this is the definition of the `System.out.println()` method. If the method returns some data, then the type of the returned data is specified instead of *void*

Unlike ordinary data, methods perform actions, so their names should almost always be verbs: "build something", "draw something", "open something".

Everything described inside the curly braces `{}` is called the **method body**. Any code can be written inside the body. Consider it a small independent program, a set of arbitrary instructions.

The body is executed exactly at the moment the method is launched. Moreover, each call of the method runs the body independently of the other calls. By the way, the body can be empty:

```java
// The minimal definition of a method
public class App {
public static void noop() {
// There could be code here, but there is none
// Pay attention to the indentation
// For readability, any code inside the body is shifted 4 spaces to the right
}
}
App.noop();
```

The notion of "creating a method" has many synonyms: "implementing", "defining", and even "coding it up". All these terms are found in everyday practice at work.

## Reuse and readability

Methods help avoid duplication. Suppose the same set of actions appears several times in a program:

```java
System.out.println("Hello, Hexlet!");
System.out.println("Hello, world!");
System.out.println("Hello, Java!");
```

Such a pattern can be gathered into one method and called in different places. When the text needs to be changed, the fix is made in one place — in the definition of the method. The bigger the project and the more often the logic repeats, the more noticeable the gain.

The name of the method itself hints at what it does. The `showCurrentDate()` method tells about its task without additional comments. This helps other programmers read the code, and also helps you yourself a month after writing it.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
name: Creating (defining) a method
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)
Original file line number Diff line number Diff line change
@@ -1,80 +1,105 @@
La definición de métodos propios simplifica en gran medida la escritura y el mantenimiento de programas. Por ejemplo, los métodos permiten combinar operaciones compuestas en una sola.
La definición de métodos propios simplifica en gran medida la escritura y el mantenimiento de los programas. Por ejemplo, los métodos permiten combinar operaciones compuestas en una sola.

Por ejemplo, enviar un correo electrónico en un sitio web es un proceso bastante complejo que implica interactuar con Internet. Se puede definir un método y ocultar toda la complejidad detrás de una sola construcción simple:
Enviar un correo desde un sitio web es un proceso complejo que incluye la interacción con internet. Se puede definir un método y ocultar toda esa complejidad detrás de una construcción corta:

```java
// Lugar donde se encuentra el método
// El lugar de donde se toma el método
import com.example.Mailer;

var email = "support@hexlet.io";
var title = "Ayuda";
var body = "He escrito una historia de éxito, ¿cómo puedo obtener un descuento?";

// Mailer - nombre de la clase en la que se define el método send()
// Una pequeña llamada - y mucha lógica interna
// Mailer es el nombre de la clase en la que está definido el método send()
// Una llamada pequeña, y mucha lógica dentro
Mailer.send(email, title, body);
```

Este tipo de llamada realiza bastante lógica interna. Se conecta al servidor de correo, forma una solicitud correcta basada en el encabezado y el cuerpo del mensaje, y luego lo envía todo, sin olvidar cerrar la conexión.
Por dentro, una llamada como esta ejecuta bastante lógica. Se conecta al servidor de correo, forma la petición correcta a partir del asunto y del cuerpo del mensaje, y luego lo envía todo, sin olvidar cerrar la conexión.

Check notice on line 18 in modules/40-methods-definition/100-method-definition-static/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-methods-definition/100-method-definition-static/es/README.md#L18

It appears that a hyphen is missing in the noun “to-do” (= task) or did you mean the verb “to do”? (TO_DO_HYPHEN[3]) Suggestions: `to-do`, `to do` URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=3 Category: GRAMMAR
Raw output
modules/40-methods-definition/100-method-definition-static/es/README.md:18:168: It appears that a hyphen is missing in the noun “to-do” (= task) or did you mean the verb “to do”? (TO_DO_HYPHEN[3])
 Suggestions: `to-do`, `to do`
 URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens 
 Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=3
 Category: GRAMMAR

## Cómo crear métodos

Crearemos nuestro primer método. Su tarea es mostrar la fecha actual en la pantalla:
Vamos a crear nuestro primer método. Su tarea es mostrar la fecha actual en la pantalla:

```text
Hoy es: 2021-10-25
Today is: 2021-10-25
```

```java
import java.time.LocalDate;

// Definición del método
// La definición no llama ni ejecuta el método
// Solo estamos diciendo que ahora existe este método
// Solo decimos que ahora ese método existe
public class App {
public static void showCurrentDate() {
// Método incorporado en Java para obtener la fecha y hora actual
// Método incorporado en Java para obtener la fecha y la hora actuales
var currentDate = LocalDate.now();
var text = "Hoy es: " + currentDate;
var text = "Today is: " + currentDate;
System.out.println(text);
}
}

// Llamada al método
// Es obligatorio especificar el nombre de la clase
App.showCurrentDate(); // => Hoy es: 2021-10-25
// Es obligatorio indicar el nombre de la clase
App.showCurrentDate(); // => Today is: 2021-10-25
```

La definición de un método en Java implica muchas acciones que iremos viendo gradualmente.
Veamos la firma del método por partes:

```text
public static void showCurrentDate()
│ │ │ │
│ │ │ nombre del método y lista de parámetros entre paréntesis
│ │ tipo del valor devuelto
│ static — el método se llama directamente desde la clase
visibilidad del método fuera de la clase
```

La definición de un método en Java incluye muchas cosas que iremos viendo poco a poco.

Se pueden dividir en dos grupos:

* Lo que afecta el funcionamiento del propio método
* Cómo se ve este método fuera de la clase
* Lo que afecta al funcionamiento del propio método
* Cómo se ve ese método fuera de la clase

La visibilidad está determinada por la palabra *public*. Esto permite llamar a los métodos desde fuera de la clase, como en el ejemplo anterior. Además de *public*, existe *private*, que se explica en Hexlet en el curso de [POO en Java](https://codica.la/courses/java-poo-basics).
De la visibilidad se encarga la palabra *public*. Permite llamar a los métodos desde fuera de la clase, como en el ejemplo anterior. Además de ella existe *private*, que se estudia en Hexlet en el curso de [POO en Java](https://codica.la/carreras/java).

El funcionamiento del método está determinado por:
Del funcionamiento del método se encargan:

* *static* - desvincula el método del objeto y permite llamarlo directamente desde la clase
* *void* se utiliza si el método no devuelve nada. Por ejemplo, esta es la definición del método `System.out.println()`. Si el método devuelve algún dato, en lugar de *void* se especifica el tipo de dato devuelto
* *static* desvincula el método del objeto y hace posible llamarlo directamente desde la clase
* *void* se usa si el método no devuelve nada. Por ejemplo, esa es la definición del método `System.out.println()`. Si el método devuelve algún dato, en lugar de *void* se indica el tipo de los datos devueltos

A diferencia de los datos normales, los métodos realizan acciones, por lo que sus nombres casi siempre deben ser verbos: "construir algo", "dibujar algo", "abrir algo".
A diferencia de los datos normales, los métodos realizan acciones, por eso sus nombres casi siempre deben ser verbos: "construir algo", "dibujar algo", "abrir algo".

Todo lo que se describe dentro de las llaves `{}` se llama **cuerpo del método**. Dentro del cuerpo se puede escribir cualquier código. Considéralo como un pequeño programa independiente, un conjunto de instrucciones arbitrarias.
Todo lo que se describe dentro de las llaves `{}` se llama **cuerpo del método**. Dentro del cuerpo se puede escribir cualquier código. Considéralo un pequeño programa independiente, un conjunto de instrucciones arbitrarias.

Check notice on line 75 in modules/40-methods-definition/100-method-definition-static/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-methods-definition/100-method-definition-static/es/README.md#L75

Possible spelling mistake found. (EN_MULTITOKEN_SPELLING_TWO[2]) Suggestions: `El Cerro` Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=2 Category: MULTITOKEN_SPELLING
Raw output
modules/40-methods-definition/100-method-definition-static/es/README.md:75:152: Possible spelling mistake found. (EN_MULTITOKEN_SPELLING_TWO[2])
 Suggestions: `El Cerro`
 Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=2
 Category: MULTITOKEN_SPELLING

El cuerpo se ejecuta exactamente en el momento en que se inicia el método. Además, cada llamada al método ejecuta el cuerpo de forma independiente de otras llamadas. Por cierto, el cuerpo puede estar vacío:
El cuerpo se ejecuta exactamente en el momento en que se lanza el método. Además, cada llamada al método ejecuta el cuerpo de forma independiente de las demás llamadas. Por cierto, el cuerpo puede estar vacío:

```java
// Definición mínima del método
// Definición mínima de un método
public class App {
public static void noop() {
// Aquí podría haber código, pero no lo hay
// Presta atención a la indentación
// Para mayor legibilidad, cualquier código dentro del cuerpo se desplaza a la derecha en 4 espacios
// Fíjate en la indentación
// Para mayor legibilidad, cualquier código dentro del cuerpo se desplaza 4 espacios a la derecha
}
}
App.noop();
```

El concepto de "crear un método" tiene muchos sinónimos: "implementar", "definir" e incluso "implementar". Todos estos términos se encuentran en la práctica diaria en el trabajo.
El concepto de "crear un método" tiene muchos sinónimos: "implementar", "definir" e incluso "codificar". Todos estos términos se encuentran en la práctica diaria del trabajo.

Check notice on line 91 in modules/40-methods-definition/100-method-definition-static/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-methods-definition/100-method-definition-static/es/README.md#L91

It appears that a hyphen is missing in the plural noun “to-dos”? (TO_DO_HYPHEN[4]) Suggestions: `To-dos` URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=4 Category: GRAMMAR
Raw output
modules/40-methods-definition/100-method-definition-static/es/README.md:91:13: It appears that a hyphen is missing in the plural noun “to-dos”? (TO_DO_HYPHEN[4])
 Suggestions: `To-dos`
 URL: https://languagetool.org/insights/post/hyphen/#compound-adjectives-with-hyphens 
 Rule: https://community.languagetool.org/rule/show/TO_DO_HYPHEN?lang=en-US&subId=4
 Category: GRAMMAR

Check notice on line 91 in modules/40-methods-definition/100-method-definition-static/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-methods-definition/100-method-definition-static/es/README.md#L91

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/40-methods-definition/100-method-definition-static/es/README.md:91:135: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC

## Reutilización y legibilidad

Los métodos ayudan a evitar la duplicación. Supongamos que en el programa aparece varias veces el mismo conjunto de acciones:

```java
System.out.println("Hello, Hexlet!");
System.out.println("Hello, world!");
System.out.println("Hello, Java!");
```

Ese patrón se puede reunir en un solo método y llamarlo en distintos lugares. Cuando haya que cambiar el texto, la corrección se hace en un único lugar: en la definición del método. Cuanto más grande es el proyecto y más a menudo se repite la lógica, más notable es la ganancia.

El nombre del método por sí mismo indica qué hace. El método `showCurrentDate()` habla de su tarea sin comentarios adicionales. Esto ayuda a otros programadores a leer el código, y también a ti mismo un mes después de haberlo escrito.

Check notice on line 105 in modules/40-methods-definition/100-method-definition-static/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-methods-definition/100-method-definition-static/es/README.md#L105

Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN) Suggestions: `an` URL: https://languagetool.org/insights/post/indefinite-articles/ Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US Category: MISC
Raw output
modules/40-methods-definition/100-method-definition-static/es/README.md:105:30: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’. (EN_A_VS_AN)
 Suggestions: `an`
 URL: https://languagetool.org/insights/post/indefinite-articles/ 
 Rule: https://community.languagetool.org/rule/show/EN_A_VS_AN?lang=en-US
 Category: MISC
11 changes: 11 additions & 0 deletions modules/40-methods-definition/150-method-main/en/EXERCISE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@

Implement a class named `App` with two methods:

1. The method `gogo()`, which prints the string `It works!` to the screen
2. `main()`, as in the definition above, which calls the `gogo()` method

The result of calling `main()` in that case will be:

```java
// => "It works!"
```
96 changes: 96 additions & 0 deletions modules/40-methods-definition/150-method-main/en/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
You may be surprised, but throughout all the previous lessons we have been creating our own method. The skeleton of the method was written in advance, and you were required to add its body. The practice looked like this:

```java
public class App {
public static void main(String[] args) {
// BEGIN
// And here you wrote your code
// END
}
}
```

Why did we create a method? Java is designed in such a way that it is impossible to execute code outside methods. You cannot just write code at the file level and run it. The compiler will report an error:

```java
// A file with such code does not compile
System.out.println("Although it would seem so");
```

But this code will already work:

```java
public class App {
public static void main(String[] args) {
System.out.println("Although it would seem so");
}
}
```

At work you will often see examples outside methods. Why do we and others do that? Purely for convenience.

Check notice on line 30 in modules/40-methods-definition/150-method-main/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-methods-definition/150-method-main/en/README.md#L30

A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1]) Suggestions: `work,` 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/40-methods-definition/150-method-main/en/README.md:30:3: A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1])
 Suggestions: `work,`
 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

If you add a wrapper in the form of a class and a method to every single line, the amount of noise and material grows significantly. Always keep this in mind, because the authors of such materials count on you understanding how Java works.

When you see code that is called without methods, always add the wrapper as shown above. Then you can easily run that code, for example, locally.

## The main method

Why is the method in our examples called `main`? After all, we could have written an example like this:

```java
public class App {
// run - the name is chosen arbitrarily
// the name can be anything the author of the code wants
public static void run() {
// some code here
}
}
```

We could have done that, and everything would work, but there is one point. In this form the `main` method, the way we define it, has a special meaning for Java.

Java calls it automatically when the program is launched from the console:

```bash
# The App file contains a class named App
java App.java # compiles and runs for execution
# Inside, the App.main method will be launched, if it is defined

Check notice on line 57 in modules/40-methods-definition/150-method-main/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-methods-definition/150-method-main/en/README.md#L57

If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1]) Suggestions: ` Main`, ` main` Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1 Category: CASING
Raw output
modules/40-methods-definition/150-method-main/en/README.md:57:18: If a new sentence starts here, add a space and start with an uppercase letter. (LC_AFTER_PERIOD[1])
 Suggestions: ` Main`, ` main`
 Rule: https://community.languagetool.org/rule/show/LC_AFTER_PERIOD?lang=en-US&subId=1
 Category: CASING
```

Any other method is not called automatically. That is exactly why we use `main` everywhere, because this way you can easily move the code from the exercise to your own editor and run it.

Is it required to define it? No, Java does not impose any restriction on which methods and how many of them you define in a class.
Just as there is no restriction on the number and the names of classes.

For simplicity we always use the name `App`, but in real code you will come across thousands of different names and classes. Although with the condition that a single file contains exactly one class:

Check notice on line 65 in modules/40-methods-definition/150-method-main/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/40-methods-definition/150-method-main/en/README.md#L65

A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1]) Suggestions: `simplicity,` 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/40-methods-definition/150-method-main/en/README.md:65:4: A comma is probably missing here. (MISSING_COMMA_AFTER_INTRODUCTORY_PHRASE[1])
 Suggestions: `simplicity,`
 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

```java
class MySuperClassName {
public static void oneMethod() {
}
public static void twoMethod() {
}
public static void threeMethod() {
}
}
```

We will talk about this in the [Java OOP](https://ru.hexlet.io/programs/java?utm_source=code-basics&utm_medium=referral&utm_campaign=programs&utm_content=lesson) course.

The main thing to remember now is that any static methods are called through a dot after the class name, and the calls themselves happen inside other methods:

```java
// Just an example of methods calling each other
class MySuperClassName {
public static void oneMethod() {
MySuperClassName.twoMethod();
}

public static void twoMethod() {
MySuperClassName.threeMethod();
}

public static void threeMethod() {
}
}
```
2 changes: 2 additions & 0 deletions modules/40-methods-definition/150-method-main/en/data.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
name: The main method
2 changes: 1 addition & 1 deletion modules/40-methods-definition/150-method-main/es/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class MySuperClassName {
}
```

Hablaremos de esto en el curso de [POO en Java](https://codica.la/courses/java-poo-basics).
Hablaremos de esto en el curso de [POO en Java](https://codica.la/carreras/java).

Lo más importante que debes recordar ahora es que cualquier método estático se llama usando un punto después del nombre de la clase, y las llamadas en sí se realizan dentro de otros métodos:

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

Implement a static method named `sayHurrayThreeTimes()` that returns the string 'hurray! hurray! hurray!'.

```java
var hurray = App.sayHurrayThreeTimes();
System.out.println(hurray); // => hurray! hurray! hurray!
```
Loading
Loading