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
80 changes: 80 additions & 0 deletions modules/35-methods-using/400-stdlib/en/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,83 @@
- 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. 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. 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)` |
| --- | --- | --- |
| `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` |

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
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.

Check notice on line 73 in modules/35-methods-using/400-stdlib/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-methods-using/400-stdlib/en/README.md#L73

Did you mean “number of”? (A_NUMBER_NNS[1]) Suggestions: `number of` Rule: https://community.languagetool.org/rule/show/A_NUMBER_NNS?lang=en-US&subId=1 Category: GRAMMAR
Raw output
modules/35-methods-using/400-stdlib/en/README.md:73:182: Did you mean “number of”? (A_NUMBER_NNS[1])
 Suggestions: `number of`
 Rule: https://community.languagetool.org/rule/show/A_NUMBER_NNS?lang=en-US&subId=1
 Category: GRAMMAR

## 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)` |

Check notice on line 82 in modules/35-methods-using/400-stdlib/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-methods-using/400-stdlib/en/README.md#L82

Articles like ‘a’ are rarely followed by punctuation. A word may be missing after ‘a’, or the punctuation mark may not be necessary. (THE_PUNCT[1]) Suggestions: `a` Rule: https://community.languagetool.org/rule/show/THE_PUNCT?lang=en-US&subId=1 Category: GRAMMAR
Raw output
modules/35-methods-using/400-stdlib/en/README.md:82:18: Articles like ‘a’ are rarely followed by punctuation. A word may be missing after ‘a’, or the punctuation mark may not be necessary. (THE_PUNCT[1])
 Suggestions: `a`
 Rule: https://community.languagetool.org/rule/show/THE_PUNCT?lang=en-US&subId=1
 Category: GRAMMAR
| `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.

Check notice on line 85 in modules/35-methods-using/400-stdlib/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-methods-using/400-stdlib/en/README.md#L85

Articles like ‘a’ are rarely followed by punctuation. A word may be missing after ‘a’, or the punctuation mark may not be necessary. (THE_PUNCT[1]) Suggestions: `a` Rule: https://community.languagetool.org/rule/show/THE_PUNCT?lang=en-US&subId=1 Category: GRAMMAR
Raw output
modules/35-methods-using/400-stdlib/en/README.md:85:45: Articles like ‘a’ are rarely followed by punctuation. A word may be missing after ‘a’, or the punctuation mark may not be necessary. (THE_PUNCT[1])
 Suggestions: `a`
 Rule: https://community.languagetool.org/rule/show/THE_PUNCT?lang=en-US&subId=1
 Category: GRAMMAR

Check notice on line 85 in modules/35-methods-using/400-stdlib/en/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-methods-using/400-stdlib/en/README.md#L85

There appears to be an unneeded comma here. “Neither…nor” is a correlative conjunction, so a comma should not separate the conjunctions. (NEITHER_NOR_SUPERFLUOUS_COMMA[2]) Suggestions: `` URL: https://languagetool.org/insights/post/word-choice-either-or-neither/ Rule: https://community.languagetool.org/rule/show/NEITHER_NOR_SUPERFLUOUS_COMMA?lang=en-US&subId=2 Category: PUNCTUATION
Raw output
modules/35-methods-using/400-stdlib/en/README.md:85:233: There appears to be an unneeded comma here. “Neither…nor” is a correlative conjunction, so a comma should not separate the conjunctions. (NEITHER_NOR_SUPERFLUOUS_COMMA[2])
 Suggestions: ``
 URL: https://languagetool.org/insights/post/word-choice-either-or-neither/ 
 Rule: https://community.languagetool.org/rule/show/NEITHER_NOR_SUPERFLUOUS_COMMA?lang=en-US&subId=2
 Category: PUNCTUATION

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.
80 changes: 80 additions & 0 deletions modules/35-methods-using/400-stdlib/es/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,83 @@
- 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 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. 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.

Check notice on line 46 in modules/35-methods-using/400-stdlib/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-methods-using/400-stdlib/es/README.md#L46

Possible spelling mistakes found. (EN_MULTITOKEN_SPELLING_TWO[1]) Suggestions: `Los Cabos` Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=1 Category: MULTITOKEN_SPELLING
Raw output
modules/35-methods-using/400-stdlib/es/README.md:46:123: Possible spelling mistakes found. (EN_MULTITOKEN_SPELLING_TWO[1])
 Suggestions: `Los Cabos`
 Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=1
 Category: MULTITOKEN_SPELLING
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)` |
| --- | --- | --- |
| `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` |

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
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.

Check notice on line 77 in modules/35-methods-using/400-stdlib/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-methods-using/400-stdlib/es/README.md#L77

Possible spelling mistake found. (EN_MULTITOKEN_SPELLING_TWO[2]) Suggestions: `El Topo` Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=2 Category: MULTITOKEN_SPELLING
Raw output
modules/35-methods-using/400-stdlib/es/README.md:77:85: Possible spelling mistake found. (EN_MULTITOKEN_SPELLING_TWO[2])
 Suggestions: `El Topo`
 Rule: https://community.languagetool.org/rule/show/EN_MULTITOKEN_SPELLING_TWO?lang=en-US&subId=2
 Category: MULTITOKEN_SPELLING

| 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 |

Check notice on line 81 in modules/35-methods-using/400-stdlib/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-methods-using/400-stdlib/es/README.md#L81

Articles like ‘a’ are rarely followed by punctuation. A word may be missing after ‘a’, or the punctuation mark may not be necessary. (THE_PUNCT[1]) Suggestions: `a` Rule: https://community.languagetool.org/rule/show/THE_PUNCT?lang=en-US&subId=1 Category: GRAMMAR
Raw output
modules/35-methods-using/400-stdlib/es/README.md:81:54: Articles like ‘a’ are rarely followed by punctuation. A word may be missing after ‘a’, or the punctuation mark may not be necessary. (THE_PUNCT[1])
 Suggestions: `a`
 Rule: https://community.languagetool.org/rule/show/THE_PUNCT?lang=en-US&subId=1
 Category: GRAMMAR
| `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 |

Check notice on line 83 in modules/35-methods-using/400-stdlib/es/README.md

View workflow job for this annotation

GitHub Actions / LanguageTool

[LanguageTool] modules/35-methods-using/400-stdlib/es/README.md#L83

Articles like ‘a’ are rarely followed by punctuation. A word may be missing after ‘a’, or the punctuation mark may not be necessary. (THE_PUNCT[1]) Suggestions: `a` Rule: https://community.languagetool.org/rule/show/THE_PUNCT?lang=en-US&subId=1 Category: GRAMMAR
Raw output
modules/35-methods-using/400-stdlib/es/README.md:83:93: Articles like ‘a’ are rarely followed by punctuation. A word may be missing after ‘a’, or the punctuation mark may not be necessary. (THE_PUNCT[1])
 Suggestions: `a`
 Rule: https://community.languagetool.org/rule/show/THE_PUNCT?lang=en-US&subId=1
 Category: GRAMMAR

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.
Loading
Loading