Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Creación de Nuestros Propios Métodos | Métodos
Java Avanzado
course content

Contenido del Curso

Java Avanzado

Java Avanzado

1. Estructura Profunda de Java
2. Métodos
3. String Avanzado
4. Clases
5. Clases Avanzadas

book
Creación de Nuestros Propios Métodos

¿Cómo usar métodos?

Hemos visto cómo crear un método que suma dos números. Ahora veamos cómo podemos llamar realmente a este método en nuestro código:

Main.java

Main.java

copy
123456789101112131415161718192021
package com.example; // do not modify the code below this comment public class Main { public static void main(String[] args) { int a = 10; int b = 31; // use the method to add two numbers: `a` and `b` int sum = addTwoNumbers(a, b); // print the sum of the two numbers System.out.println(sum); } // method to add two numbers and return the result static int addTwoNumbers(int firstNumber, int secondNumber) { int result = firstNumber + secondNumber; // return the result of the addition return result; } }
  • Creamos dos variables de tipo int con valores diferentes y luego las pasamos como parámetros a nuestro método;
  • Dado que nuestro método retorna un tipo int, podemos inicializar la variable sum con el resultado de llamar al método;
  • Así, nuestro método calculó y devolvió la sum de los dos números.

También podemos pasar arreglos como parámetros y devolverlos desde los métodos. Veamos un ejemplo:

Main.java

Main.java

copy
1234567891011121314151617181920212223242526272829303132
package com.example; import java.util.Arrays; // do not modify the code below this comment public class Main { public static void main(String[] args) { // creating an unsorted array int[] array = {4, -1, 5, 0, 4, -6, 2, 7, 4, 1}; // use a method to sort the array and increment each element by 1 int[] newArray = sortAndIncrementEveryElement(array); // print the new array after sorting and incrementing each element for (int element : newArray) { System.out.print(element + " "); // output each element from the new array } } // method to increment each element of the array by 1 and then sort it static int[] sortAndIncrementEveryElement(int[] inputArray) { // create a result array with the same length as the input array int[] result = new int[inputArray.length]; // increment each element by 1 for (int i = 0; i < inputArray.length; i++) { result[i] = inputArray[i] + 1; } // sort the result array Arrays.sort(result); // return the sorted and incremented array return result; } }

Hemos escrito un método que ordena e incrementa cada elemento de un arreglo de enteros (int[]). Luego creamos un arreglo desordenado y utilizamos el método sobre él, inicializando un nuevo arreglo llamado newArray con el valor devuelto.

Cabe destacar que podemos utilizar este método varias veces en el mismo código, por ejemplo:

Main.java

Main.java

copy
1234567891011121314151617181920212223242526272829303132333435363738
package com.example; import java.util.Arrays; // do not modify the code below this comment public class Main { public static void main(String[] args) { // creating unsorted arrays int[] array = {4, -1, 5, 0, 4, -6, 2, 7, 4, 1}; int[] secondArray = {2, 2, 0, -5, 1, 8, 13, -9, 0}; // use a method to sort and increment each element in both arrays int[] newArray = sortAndIncrementEveryElement(array); int[] newSecondArray = sortAndIncrementEveryElement(secondArray); // print the new arrays after sorting and incrementing the elements for (int element : newArray) { System.out.print(element + " "); // output each element of the first array } System.out.println(System.lineSeparator()); for (int element : newSecondArray) { System.out.print(element + " "); // output each element of the second array } } // method to increment each element by 1 and then sort the array static int[] sortAndIncrementEveryElement(int[] inputArray) { // create a result array with the same length as the input array int[] result = new int[inputArray.length]; // increment each element by 1 for (int i = 0; i < inputArray.length; i++) { result[i] = inputArray[i] + 1; } // sort the result array Arrays.sort(result); // return the sorted and incremented array return result; } }

Así, podemos observar que podemos utilizar nuestro método varias veces en el código. Lo hemos aplicado a dos arreglos de enteros diferentes, y cada uno de ellos ahora está ordenado e incrementado.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 2

Pregunte a AI

expand

Pregunte a AI

ChatGPT

Pregunte lo que quiera o pruebe una de las preguntas sugeridas para comenzar nuestra charla

course content

Contenido del Curso

Java Avanzado

Java Avanzado

1. Estructura Profunda de Java
2. Métodos
3. String Avanzado
4. Clases
5. Clases Avanzadas

book
Creación de Nuestros Propios Métodos

¿Cómo usar métodos?

Hemos visto cómo crear un método que suma dos números. Ahora veamos cómo podemos llamar realmente a este método en nuestro código:

Main.java

Main.java

copy
123456789101112131415161718192021
package com.example; // do not modify the code below this comment public class Main { public static void main(String[] args) { int a = 10; int b = 31; // use the method to add two numbers: `a` and `b` int sum = addTwoNumbers(a, b); // print the sum of the two numbers System.out.println(sum); } // method to add two numbers and return the result static int addTwoNumbers(int firstNumber, int secondNumber) { int result = firstNumber + secondNumber; // return the result of the addition return result; } }
  • Creamos dos variables de tipo int con valores diferentes y luego las pasamos como parámetros a nuestro método;
  • Dado que nuestro método retorna un tipo int, podemos inicializar la variable sum con el resultado de llamar al método;
  • Así, nuestro método calculó y devolvió la sum de los dos números.

También podemos pasar arreglos como parámetros y devolverlos desde los métodos. Veamos un ejemplo:

Main.java

Main.java

copy
1234567891011121314151617181920212223242526272829303132
package com.example; import java.util.Arrays; // do not modify the code below this comment public class Main { public static void main(String[] args) { // creating an unsorted array int[] array = {4, -1, 5, 0, 4, -6, 2, 7, 4, 1}; // use a method to sort the array and increment each element by 1 int[] newArray = sortAndIncrementEveryElement(array); // print the new array after sorting and incrementing each element for (int element : newArray) { System.out.print(element + " "); // output each element from the new array } } // method to increment each element of the array by 1 and then sort it static int[] sortAndIncrementEveryElement(int[] inputArray) { // create a result array with the same length as the input array int[] result = new int[inputArray.length]; // increment each element by 1 for (int i = 0; i < inputArray.length; i++) { result[i] = inputArray[i] + 1; } // sort the result array Arrays.sort(result); // return the sorted and incremented array return result; } }

Hemos escrito un método que ordena e incrementa cada elemento de un arreglo de enteros (int[]). Luego creamos un arreglo desordenado y utilizamos el método sobre él, inicializando un nuevo arreglo llamado newArray con el valor devuelto.

Cabe destacar que podemos utilizar este método varias veces en el mismo código, por ejemplo:

Main.java

Main.java

copy
1234567891011121314151617181920212223242526272829303132333435363738
package com.example; import java.util.Arrays; // do not modify the code below this comment public class Main { public static void main(String[] args) { // creating unsorted arrays int[] array = {4, -1, 5, 0, 4, -6, 2, 7, 4, 1}; int[] secondArray = {2, 2, 0, -5, 1, 8, 13, -9, 0}; // use a method to sort and increment each element in both arrays int[] newArray = sortAndIncrementEveryElement(array); int[] newSecondArray = sortAndIncrementEveryElement(secondArray); // print the new arrays after sorting and incrementing the elements for (int element : newArray) { System.out.print(element + " "); // output each element of the first array } System.out.println(System.lineSeparator()); for (int element : newSecondArray) { System.out.print(element + " "); // output each element of the second array } } // method to increment each element by 1 and then sort the array static int[] sortAndIncrementEveryElement(int[] inputArray) { // create a result array with the same length as the input array int[] result = new int[inputArray.length]; // increment each element by 1 for (int i = 0; i < inputArray.length; i++) { result[i] = inputArray[i] + 1; } // sort the result array Arrays.sort(result); // return the sorted and incremented array return result; } }

Así, podemos observar que podemos utilizar nuestro método varias veces en el código. Lo hemos aplicado a dos arreglos de enteros diferentes, y cada uno de ellos ahora está ordenado e incrementado.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 2
some-alt