From 20979c367d8f2af274365bbc02a2907d22334eb5 Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Thu, 5 Nov 2026 17:30:10 +0500 Subject: [PATCH 1/2] =?UTF-8?q?feat(stdlib):=20=D0=BE=D0=B1=D1=8A=D1=8F?= =?UTF-8?q?=D1=81=D0=BD=D0=B8=D1=82=D1=8C=20=D1=87=D1=82=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD=D1=82=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D0=B8=20Java?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: CONTENT-763 Co-Authored-By: Claude Opus 5.5 --- .../35-methods-using/400-stdlib/en/README.md | 61 +++++++++++++++++++ .../35-methods-using/400-stdlib/es/README.md | 61 +++++++++++++++++++ .../35-methods-using/400-stdlib/ru/README.md | 61 +++++++++++++++++++ 3 files changed, 183 insertions(+) diff --git a/modules/35-methods-using/400-stdlib/en/README.md b/modules/35-methods-using/400-stdlib/en/README.md index d78341d..cf86fab 100644 --- a/modules/35-methods-using/400-stdlib/en/README.md +++ b/modules/35-methods-using/400-stdlib/en/README.md @@ -9,3 +9,64 @@ Here are some tips on how to learn about new methods: - 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). + +## How to read a method's documentation + +Documentation describes what data a method accepts and what result it returns. The reference for the Java standard library is organized by classes, and each class has its own page. A class page has two sections you need to write a call. The Method Summary section lists the class's methods in a table, and the Method Details section describes each method in detail. + +Let's look at the `indexOf()` method, which searches for a substring and returns its position. Each row of the Method Summary table has three columns. The Modifier and Type column shows the result type, the Method column shows the method name with its parameters, and the Description column briefly says what it does. The table has several rows for `indexOf()`, including these two. + +```text +int indexOf(String str) +int indexOf(String str, int fromIndex) +``` + +Clicking the method name opens its description in the Method Details section. It starts with the full method declaration. + +```text +public int indexOf(String str, int fromIndex) +``` + +The table matches the parts of the declaration to the arguments of the call `"Java".indexOf("a", 2)`. + +| Part of the declaration | What it means | In the call `"Java".indexOf("a", 2)` | +| --- | --- | --- | +| `public` | The method is available from any code | We call the method from our program | +| `int` | Result type, an integer | We get the position of the character | +| `indexOf` | Method name | We call `indexOf()` on the string `"Java"` | +| `String str` | A `String` parameter, the substring to search for | We pass `"a"` | +| `int fromIndex` | An `int` parameter, the position where the search starts | We pass `2` | + +Below the declaration come the Parameters and Returns sections. The Parameters section explains each parameter. It says `fromIndex` is the index to start the search from. The Returns section describes the result. The method returns the position of the first occurrence of the substring starting at the given index, or `-1` if there is none. The declaration shows which arguments to pass, and the description explains what you get. + +```java +System.out.println("Java".indexOf("a")); // => 1 +System.out.println("Java".indexOf("a", 2)); // => 3 +System.out.println("Java".indexOf("a", 4)); // => -1 +``` + +The first call finds the first `a` at position `1`. The second starts searching at position `2` and finds the second `a` at position `3`. The third starts at position `4`, where the string has already ended, so it returns `-1`, as the Returns section promises. + +## Overloads instead of optional parameters + +In Java, method parameters have no default values. If an argument can be omitted, the class declares several methods with the same name and different parameters. These methods are called **overloads**. That's why `indexOf()` has several rows in Method Summary. The `indexOf(String str)` version searches from the beginning of the string, and the `indexOf(String str, int fromIndex)` version searches from the given position. + +Java picks the overload by the arguments of the call. The call `"Java".indexOf("a")` with one string goes to the first version, and the call `"Java".indexOf("a", 2)` with a string and a number goes to the second. To understand how the versions differ, read the description of each one. + +## Notation in the reference + +Method declarations contain auxiliary words and signs. They help you read the declaration and are not copied into the call. + +| Notation in the reference | How to read it | +| --- | --- | +| `int indexOf(String str)` | The type comes before the name. `int` to the left of the method is the result type, and `String` before `str` is the parameter type | +| `static int max(int a, int b)` | The word `static` means the method is called through the class name, for example `Math.max(3, 7)` | +| `static String join(CharSequence delimiter, CharSequence... elements)` | The ellipsis after the type means you can pass any number of arguments in that place | + +For example, the declaration `static int max(int a, int b)` from the `Math` class reference describes a method with two parameters. The call `Math.max(3, 7)` passes the numbers `3` and `7` and returns `7`. Neither `static`, nor the types, nor the names `a` and `b` go into the call. The `join()` declaration contains the `CharSequence` type. Strings fit there too, so the call `String.join(":", "8", "30")` works the same way as in the lesson about a variable number of parameters. + +If your browser translates the page, check method names, parameter names, and types against the original. Code uses the original names from the documentation. + +## Working with an unfamiliar method + +Reading a reference starts with a task. For example, to find the second `a` in a word, we open the `String` class page, find the `indexOf()` overloads in Method Summary, read what `fromIndex` does in Method Details, and try the call `"Java".indexOf("a", 2)` in [JShell](https://onecompiler.com/jshell). If the result matches the description, the call can go into the program. diff --git a/modules/35-methods-using/400-stdlib/es/README.md b/modules/35-methods-using/400-stdlib/es/README.md index 2312b5e..e97a0ef 100644 --- a/modules/35-methods-using/400-stdlib/es/README.md +++ b/modules/35-methods-using/400-stdlib/es/README.md @@ -9,3 +9,64 @@ Aquí hay algunos consejos sobre cómo aprender sobre nuevos métodos: - 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). + +## Cómo leer la documentación de un método + +La documentación describe qué datos recibe un método y qué resultado devuelve. La referencia de la biblioteca estándar de Java está organizada por clases, y cada clase tiene su propia página. En la página de una clase hay dos secciones que hacen falta para escribir una llamada. La sección Method Summary enumera los métodos de la clase en una tabla, y la sección Method Details describe cada método en detalle. + +Veamos el método `indexOf()`, que busca una subcadena y devuelve su posición. En la tabla Method Summary cada fila tiene tres columnas. La columna Modifier and Type muestra el tipo del resultado, la columna Method muestra el nombre del método con sus parámetros, y la columna Description resume lo que hace. Para `indexOf()` la tabla tiene varias filas, entre ellas estas dos. + +```text +int indexOf(String str) +int indexOf(String str, int fromIndex) +``` + +Al hacer clic en el nombre del método se abre su descripción en la sección Method Details. Empieza con la declaración completa del método. + +```text +public int indexOf(String str, int fromIndex) +``` + +La tabla relaciona las partes de la declaración con los argumentos de la llamada `"Java".indexOf("a", 2)`. + +| Parte de la declaración | Qué significa | En la llamada `"Java".indexOf("a", 2)` | +| --- | --- | --- | +| `public` | El método está disponible desde cualquier código | Llamamos al método desde nuestro programa | +| `int` | Tipo del resultado, un número entero | Obtenemos la posición del carácter | +| `indexOf` | Nombre del método | Llamamos a `indexOf()` sobre la cadena `"Java"` | +| `String str` | Parámetro de tipo `String`, la subcadena que se busca | Pasamos `"a"` | +| `int fromIndex` | Parámetro de tipo `int`, la posición donde empieza la búsqueda | Pasamos `2` | + +Debajo de la declaración están las secciones Parameters y Returns. La sección Parameters explica cada parámetro. De `fromIndex` dice que es el índice desde el que empieza la búsqueda. La sección Returns describe el resultado. El método devuelve la posición de la primera aparición de la subcadena a partir del índice indicado, o `-1` si no la encuentra. La declaración muestra qué argumentos pasar, y la descripción explica qué se obtiene. + +```java +System.out.println("Java".indexOf("a")); // => 1 +System.out.println("Java".indexOf("a", 2)); // => 3 +System.out.println("Java".indexOf("a", 4)); // => -1 +``` + +La primera llamada encuentra la primera `a` en la posición `1`. La segunda empieza a buscar en la posición `2` y encuentra la segunda `a` en la posición `3`. La tercera empieza en la posición `4`, donde la cadena ya terminó, así que devuelve `-1`, tal como indica la sección Returns. + +## Sobrecargas en lugar de parámetros opcionales + +En Java los parámetros de un método no tienen valores por defecto. Si un argumento se puede omitir, la clase declara varios métodos con el mismo nombre y distintos parámetros. Estos métodos se llaman **sobrecargas**. Por eso en Method Summary `indexOf()` aparece en varias filas. La versión `indexOf(String str)` busca desde el principio de la cadena, y la versión `indexOf(String str, int fromIndex)` busca desde la posición indicada. + +Java elige la sobrecarga según los argumentos de la llamada. La llamada `"Java".indexOf("a")` con una cadena va a la primera versión, y la llamada `"Java".indexOf("a", 2)` con una cadena y un número va a la segunda. Para saber en qué se diferencian las versiones, se lee la descripción de cada una. + +## Notación en la referencia + +En las declaraciones de los métodos aparecen palabras y signos auxiliares. Ayudan a leer la declaración y no se copian en la llamada. + +| Notación en la referencia | Cómo leerla | +| --- | --- | +| `int indexOf(String str)` | El tipo va delante del nombre. `int` a la izquierda del método es el tipo del resultado, y `String` delante de `str` es el tipo del parámetro | +| `static int max(int a, int b)` | La palabra `static` indica que el método se llama a través del nombre de la clase, por ejemplo `Math.max(3, 7)` | +| `static String join(CharSequence delimiter, CharSequence... elements)` | Los puntos suspensivos después del tipo indican que en ese lugar se puede pasar cualquier cantidad de argumentos | + +Por ejemplo, la declaración `static int max(int a, int b)` de la referencia de la clase `Math` describe un método con dos parámetros. La llamada `Math.max(3, 7)` pasa los números `3` y `7` y devuelve `7`. Ni `static`, ni los tipos, ni los nombres `a` y `b` se copian en la llamada. En la declaración de `join()` aparece el tipo `CharSequence`. En su lugar también sirven cadenas, por eso la llamada `String.join(":", "8", "30")` funciona igual que en la lección sobre la cantidad variable de parámetros. + +Si el navegador traduce la página, hay que comparar los nombres de métodos y parámetros y los tipos con el original. En el código se usan los nombres originales de la documentación. + +## Trabajar con un método desconocido + +La lectura de la referencia empieza por la tarea. Por ejemplo, para encontrar la segunda `a` de una palabra, abrimos la página de la clase `String`, en Method Summary buscamos las sobrecargas de `indexOf()`, en Method Details leemos qué hace `fromIndex` y probamos la llamada `"Java".indexOf("a", 2)` en [JShell](https://onecompiler.com/jshell). Si el resultado coincide con la descripción, la llamada se puede usar en el programa. diff --git a/modules/35-methods-using/400-stdlib/ru/README.md b/modules/35-methods-using/400-stdlib/ru/README.md index c9a7b7d..982f67d 100644 --- a/modules/35-methods-using/400-stdlib/ru/README.md +++ b/modules/35-methods-using/400-stdlib/ru/README.md @@ -9,3 +9,64 @@ Java, как и любой другой язык, поставляется с н - Чаще читайте чужой код, особенно код библиотек, которые вы используете. Он весь доступен на GitHub Предположим, нужно убрать пробелы по краям строки. Для поиска подходит [документация класса `String`](https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/lang/String.html). Раздел Method Summary содержит список методов с краткими описаниями. В нём `trim()` описан как метод, возвращающий строку без начальных и конечных пробелов. По ссылке `trim()` открывается подробный контракт. Для строки `" Java "` вызов `trim()` возвращает `"Java"`. Числовые операции, например модуль числа, находятся в [документации класса `Math`](https://docs.oracle.com/en/java/javase/26/docs/api/java.base/java/lang/Math.html). + +## Как читать документацию метода + +Документация описывает, какие данные принимает метод и какой результат возвращает. Справка о стандартной библиотеке Java собрана по классам, и у каждого класса своя страница. На странице класса есть два раздела, которые нужны для вызова. Раздел Method Summary перечисляет методы класса таблицей, а раздел Method Details подробно описывает каждый метод. + +Разберём метод `indexOf()`, который ищет подстроку и возвращает её позицию. В таблице Method Summary у каждой строки три колонки. Колонка Modifier and Type показывает тип результата, колонка Method показывает имя метода с параметрами, а колонка Description кратко описывает работу. Для `indexOf()` в таблице несколько строк, среди них такие две. + +```text +int indexOf(String str) +int indexOf(String str, int fromIndex) +``` + +Если щёлкнуть по имени метода, откроется его описание в разделе Method Details. Оно начинается с полной записи метода. + +```text +public int indexOf(String str, int fromIndex) +``` + +В таблице сопоставлены части записи и аргументы вызова `"Java".indexOf("a", 2)`. + +| Часть записи | Что она означает | В вызове `"Java".indexOf("a", 2)` | +| --- | --- | --- | +| `public` | Метод доступен из любого кода | Вызываем метод из своей программы | +| `int` | Тип результата, целое число | Получаем позицию символа | +| `indexOf` | Имя метода | Вызываем `indexOf()` у строки `"Java"` | +| `String str` | Параметр типа `String`, подстрока для поиска | Передаём `"a"` | +| `int fromIndex` | Параметр типа `int`, позиция начала поиска | Передаём `2` | + +Под записью идут разделы Parameters и Returns. Раздел Parameters объясняет каждый параметр. О `fromIndex` там сказано, что это индекс, с которого начинается поиск. Раздел Returns описывает результат. Метод возвращает позицию первого вхождения подстроки, начиная с указанного индекса, или `-1`, если подстроки там нет. Запись показывает, какие аргументы передать, а описание объясняет, что получится. + +```java +System.out.println("Java".indexOf("a")); // => 1 +System.out.println("Java".indexOf("a", 2)); // => 3 +System.out.println("Java".indexOf("a", 4)); // => -1 +``` + +Первый вызов находит первую букву `a` на позиции `1`. Второй начинает поиск с позиции `2` и находит вторую букву `a` на позиции `3`. Третий начинает с позиции `4`, где строка уже закончилась, поэтому возвращает `-1`, как и обещает раздел Returns. + +## Перегрузки вместо необязательных параметров + +В Java у параметров метода нет значений по умолчанию. Если аргумент можно не передавать, в классе объявлено несколько методов с одним именем и разными параметрами. Такие методы называются **перегрузками**. Поэтому в Method Summary у `indexOf()` несколько строк. Версия `indexOf(String str)` ищет с начала строки, а версия `indexOf(String str, int fromIndex)` ищет с указанной позиции. + +Java выбирает перегрузку по аргументам вызова. Вызов `"Java".indexOf("a")` с одной строкой попадает в первую версию, вызов `"Java".indexOf("a", 2)` со строкой и числом попадает во вторую. Чтобы понять, чем версии отличаются, читают описание каждой из них. + +## Обозначения в справке + +В записях методов встречаются служебные слова и знаки. Они помогают прочитать запись и при вызове в код не переносятся. + +| Запись в справке | Как её читать | +| --- | --- | +| `int indexOf(String str)` | Тип стоит перед именем. `int` слева от метода это тип результата, `String` перед `str` это тип параметра | +| `static int max(int a, int b)` | Слово `static` означает, что метод вызывают через имя класса, например `Math.max(3, 7)` | +| `static String join(CharSequence delimiter, CharSequence... elements)` | Многоточие после типа означает, что на этом месте можно передать любое количество аргументов | + +Например, запись `static int max(int a, int b)` из справки класса `Math` описывает метод с двумя параметрами. Вызов `Math.max(3, 7)` передаёт числа `3` и `7` и возвращает `7`. Ни `static`, ни типы, ни имена `a` и `b` в вызов не копируются. В записи `join()` встречается тип `CharSequence`. На его место подходят и строки, поэтому вызов `String.join(":", "8", "30")` работает так же, как в уроке о переменном числе параметров. + +Если браузер переводит страницу, имена методов, параметров и типы нужно сверять с оригиналом. В коде используются исходные имена из документации. + +## Работа с незнакомым методом + +Чтение справки начинается с задачи. Например, чтобы найти вторую букву `a` в слове, открываем страницу класса `String`, в Method Summary находим перегрузки `indexOf()`, в Method Details читаем, что делает `fromIndex`, и пробуем вызов `"Java".indexOf("a", 2)` в [JShell](https://onecompiler.com/jshell). Если результат соответствует описанию, вызов можно использовать в программе. From 1b5b8fd985d5ec95247c9873668ef98d866fd124 Mon Sep 17 00:00:00 2001 From: Nikolay Gagarinov Date: Thu, 5 Nov 2026 21:19:32 +0500 Subject: [PATCH 2/2] =?UTF-8?q?docs(stdlib):=20=D0=BF=D0=BE=D0=BA=D0=B0?= =?UTF-8?q?=D0=B7=D0=B0=D1=82=D1=8C=20=D1=84=D1=80=D0=B0=D0=B3=D0=BC=D0=B5?= =?UTF-8?q?=D0=BD=D1=82=20Method=20Details=20=D0=B2=D0=BC=D0=B5=D1=81?= =?UTF-8?q?=D1=82=D0=BE=20=D0=BF=D0=B5=D1=80=D0=B5=D1=81=D0=BA=D0=B0=D0=B7?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refs: CONTENT-763 Co-Authored-By: Claude Opus 5.5 --- .../35-methods-using/400-stdlib/en/README.md | 25 ++++++++++++++++--- .../35-methods-using/400-stdlib/es/README.md | 25 ++++++++++++++++--- .../35-methods-using/400-stdlib/ru/README.md | 25 ++++++++++++++++--- 3 files changed, 66 insertions(+), 9 deletions(-) diff --git a/modules/35-methods-using/400-stdlib/en/README.md b/modules/35-methods-using/400-stdlib/en/README.md index cf86fab..6f68cec 100644 --- a/modules/35-methods-using/400-stdlib/en/README.md +++ b/modules/35-methods-using/400-stdlib/en/README.md @@ -14,19 +14,38 @@ Suppose you need to remove spaces from the ends of a string. Start with the [doc Documentation describes what data a method accepts and what result it returns. The reference for the Java standard library is organized by classes, and each class has its own page. A class page has two sections you need to write a call. The Method Summary section lists the class's methods in a table, and the Method Details section describes each method in detail. -Let's look at the `indexOf()` method, which searches for a substring and returns its position. Each row of the Method Summary table has three columns. The Modifier and Type column shows the result type, the Method column shows the method name with its parameters, and the Description column briefly says what it does. The table has several rows for `indexOf()`, including these two. +Let's look at the `indexOf()` method, which searches for a substring and returns its position. For each method, the Method Summary table shows the result type, the name with parameters, and a short description. The table has several rows for `indexOf()`, including these two. ```text int indexOf(String str) int indexOf(String str, int fromIndex) ``` -Clicking the method name opens its description in the Method Details section. It starts with the full method declaration. +Clicking the method name opens its description in the Method Details section. Here is the description of the second version, with part of the text omitted. ```text public int indexOf(String str, int fromIndex) + +Returns the index within this string of the first occurrence of the +specified substring, starting at the specified index. +... + +Parameters: + str - the substring to search for. + fromIndex - the index from which to start the search. +Returns: + the index of the first occurrence of the specified substring, + starting at the specified index, or -1 if there is no such occurrence. ``` +Read the description from top to bottom. + +1. The first line is the method declaration with the result type, name, and parameters. +2. The first sentence briefly says what the method does. +3. Details follow. They may include formulas and notes, which you can skip on a first read. +4. The Parameters section explains each parameter by its name from the declaration. Here `fromIndex` is the index where the search starts. +5. The Returns section describes the result, including special cases. Here the method returns `-1` if the substring is not found. + The table matches the parts of the declaration to the arguments of the call `"Java".indexOf("a", 2)`. | Part of the declaration | What it means | In the call `"Java".indexOf("a", 2)` | @@ -37,7 +56,7 @@ The table matches the parts of the declaration to the arguments of the call `"Ja | `String str` | A `String` parameter, the substring to search for | We pass `"a"` | | `int fromIndex` | An `int` parameter, the position where the search starts | We pass `2` | -Below the declaration come the Parameters and Returns sections. The Parameters section explains each parameter. It says `fromIndex` is the index to start the search from. The Returns section describes the result. The method returns the position of the first occurrence of the substring starting at the given index, or `-1` if there is none. The declaration shows which arguments to pass, and the description explains what you get. +The declaration shows which arguments to pass, and the description explains what you get. Let's check it with calls. ```java System.out.println("Java".indexOf("a")); // => 1 diff --git a/modules/35-methods-using/400-stdlib/es/README.md b/modules/35-methods-using/400-stdlib/es/README.md index e97a0ef..0cdf9d2 100644 --- a/modules/35-methods-using/400-stdlib/es/README.md +++ b/modules/35-methods-using/400-stdlib/es/README.md @@ -14,19 +14,38 @@ Supongamos que hay que quitar los espacios de los extremos de una cadena. Para b La documentación describe qué datos recibe un método y qué resultado devuelve. La referencia de la biblioteca estándar de Java está organizada por clases, y cada clase tiene su propia página. En la página de una clase hay dos secciones que hacen falta para escribir una llamada. La sección Method Summary enumera los métodos de la clase en una tabla, y la sección Method Details describe cada método en detalle. -Veamos el método `indexOf()`, que busca una subcadena y devuelve su posición. En la tabla Method Summary cada fila tiene tres columnas. La columna Modifier and Type muestra el tipo del resultado, la columna Method muestra el nombre del método con sus parámetros, y la columna Description resume lo que hace. Para `indexOf()` la tabla tiene varias filas, entre ellas estas dos. +Veamos el método `indexOf()`, que busca una subcadena y devuelve su posición. En la tabla Method Summary cada método indica el tipo del resultado, el nombre con sus parámetros y una descripción breve. Para `indexOf()` la tabla tiene varias filas, entre ellas estas dos. ```text int indexOf(String str) int indexOf(String str, int fromIndex) ``` -Al hacer clic en el nombre del método se abre su descripción en la sección Method Details. Empieza con la declaración completa del método. +Al hacer clic en el nombre del método se abre su descripción en la sección Method Details. Abajo está la descripción de la segunda versión, con una parte del texto omitida. ```text public int indexOf(String str, int fromIndex) + +Returns the index within this string of the first occurrence of the +specified substring, starting at the specified index. +... + +Parameters: + str - the substring to search for. + fromIndex - the index from which to start the search. +Returns: + the index of the first occurrence of the specified substring, + starting at the specified index, or -1 if there is no such occurrence. ``` +La descripción se lee de arriba abajo, paso a paso. + +1. La primera línea contiene la declaración del método con el tipo del resultado, el nombre y los parámetros. +2. La primera oración resume qué hace el método. +3. Luego vienen los detalles. A veces incluyen fórmulas y notas, y en la primera lectura se pueden saltar. +4. La sección Parameters explica cada parámetro por el nombre que tiene en la declaración. Aquí `fromIndex` es el índice desde el que empieza la búsqueda. +5. La sección Returns describe el resultado, incluidos los casos especiales. Aquí el método devuelve `-1` si no encuentra la subcadena. + La tabla relaciona las partes de la declaración con los argumentos de la llamada `"Java".indexOf("a", 2)`. | Parte de la declaración | Qué significa | En la llamada `"Java".indexOf("a", 2)` | @@ -37,7 +56,7 @@ La tabla relaciona las partes de la declaración con los argumentos de la llamad | `String str` | Parámetro de tipo `String`, la subcadena que se busca | Pasamos `"a"` | | `int fromIndex` | Parámetro de tipo `int`, la posición donde empieza la búsqueda | Pasamos `2` | -Debajo de la declaración están las secciones Parameters y Returns. La sección Parameters explica cada parámetro. De `fromIndex` dice que es el índice desde el que empieza la búsqueda. La sección Returns describe el resultado. El método devuelve la posición de la primera aparición de la subcadena a partir del índice indicado, o `-1` si no la encuentra. La declaración muestra qué argumentos pasar, y la descripción explica qué se obtiene. +La declaración muestra qué argumentos pasar, y la descripción explica qué se obtiene. Comprobémoslo con llamadas. ```java System.out.println("Java".indexOf("a")); // => 1 diff --git a/modules/35-methods-using/400-stdlib/ru/README.md b/modules/35-methods-using/400-stdlib/ru/README.md index 982f67d..d17d447 100644 --- a/modules/35-methods-using/400-stdlib/ru/README.md +++ b/modules/35-methods-using/400-stdlib/ru/README.md @@ -14,19 +14,38 @@ Java, как и любой другой язык, поставляется с н Документация описывает, какие данные принимает метод и какой результат возвращает. Справка о стандартной библиотеке Java собрана по классам, и у каждого класса своя страница. На странице класса есть два раздела, которые нужны для вызова. Раздел Method Summary перечисляет методы класса таблицей, а раздел Method Details подробно описывает каждый метод. -Разберём метод `indexOf()`, который ищет подстроку и возвращает её позицию. В таблице Method Summary у каждой строки три колонки. Колонка Modifier and Type показывает тип результата, колонка Method показывает имя метода с параметрами, а колонка Description кратко описывает работу. Для `indexOf()` в таблице несколько строк, среди них такие две. +Разберём метод `indexOf()`, который ищет подстроку и возвращает её позицию. В таблице Method Summary у каждого метода указаны тип результата, имя с параметрами и краткое описание. Для `indexOf()` в таблице несколько строк, среди них такие две. ```text int indexOf(String str) int indexOf(String str, int fromIndex) ``` -Если щёлкнуть по имени метода, откроется его описание в разделе Method Details. Оно начинается с полной записи метода. +Если щёлкнуть по имени метода, откроется его описание в разделе Method Details. Ниже приведено описание второй версии, часть текста пропущена. ```text public int indexOf(String str, int fromIndex) + +Returns the index within this string of the first occurrence of the +specified substring, starting at the specified index. +... + +Parameters: + str - the substring to search for. + fromIndex - the index from which to start the search. +Returns: + the index of the first occurrence of the specified substring, + starting at the specified index, or -1 if there is no such occurrence. ``` +Описание читают сверху вниз по шагам. + +1. Первая строка содержит запись метода с типом результата, именем и параметрами. +2. Первое предложение кратко говорит, что делает метод. +3. Дальше идут подробности. В них бывают формулы и примечания, на первом чтении их можно пропустить. +4. Раздел Parameters объясняет каждый параметр по имени из записи. Здесь `fromIndex` означает индекс, с которого начинается поиск. +5. Раздел Returns описывает результат, включая особые случаи. Здесь метод возвращает `-1`, если подстроки нет. + В таблице сопоставлены части записи и аргументы вызова `"Java".indexOf("a", 2)`. | Часть записи | Что она означает | В вызове `"Java".indexOf("a", 2)` | @@ -37,7 +56,7 @@ public int indexOf(String str, int fromIndex) | `String str` | Параметр типа `String`, подстрока для поиска | Передаём `"a"` | | `int fromIndex` | Параметр типа `int`, позиция начала поиска | Передаём `2` | -Под записью идут разделы Parameters и Returns. Раздел Parameters объясняет каждый параметр. О `fromIndex` там сказано, что это индекс, с которого начинается поиск. Раздел Returns описывает результат. Метод возвращает позицию первого вхождения подстроки, начиная с указанного индекса, или `-1`, если подстроки там нет. Запись показывает, какие аргументы передать, а описание объясняет, что получится. +Запись показывает, какие аргументы передать, а описание объясняет, что получится. Проверим это вызовами. ```java System.out.println("Java".indexOf("a")); // => 1