Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprende Void | Métodos
Java Extendido

bookVoid

Cómo devolver nada en Java

Existe un caso especial cuando el tipo de retorno es void. Cuando el tipo de retorno es void, significa que no estamos devolviendo nada desde nuestro método. Simplemente realiza operaciones y no retorna un valor. Dicho método aún puede tener parámetros. Veamos un ejemplo de uso de un método void:

Main.java

Main.java

copy
1234567891011121314151617
package com.example; // do not modify the code below this comment public class Main { // method to print the string value passed as a parameter static void printStringValueFromParameter(String value) { System.out.println("Value from parameter: " + value); } public static void main(String[] args) { // creating a string variable to be passed as a parameter String string = "Hey, I'll be printed through a method!"; // calling the method and passing the string as a parameter printStringValueFromParameter(string); } }

Hemos escrito y utilizado un método que no devuelve nada. Este método void recibe un parámetro de tipo String y lo imprime en pantalla. Lo llamamos en el método main, y funciona correctamente.

Un método void también puede realizar operaciones más complejas sin devolver nada, como imprimir un arreglo. Será mucho más limpio cuando imprimamos un arreglo usando solo un método en el método main. Veamos un ejemplo de código:

Main.java

Main.java

copy
12345678910111213141516171819202122232425
package com.example; // do not modify the code below this comment public class Main { // method to print each element of an integer array to the console static void printIntArrayToTheConsole(int[] array) { // iterating over each element of the array and printing it for (int element : array) { System.out.print(element + " "); } // using an empty System.out.println to add a blank line in the console System.out.println(); } public static void main(String[] args) { // creating the first integer array int[] firstArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // creating the second integer array int[] secondArray = {0, 2, 4, 6, 8, 10, 12, 14, 16}; // calling the method to print both arrays printIntArrayToTheConsole(firstArray); printIntArrayToTheConsole(secondArray); } }

Como puedes ver, ahorramos líneas de código al escribir un método separado para imprimir el arreglo. En lugar de escribir repetidamente un nuevo ciclo for-each para imprimir el arreglo, simplemente llamamos a este método y pasamos el arreglo como parámetro.

De esta manera, podemos decir que los métodos mejoran considerablemente nuestro código. Lo hacen más legible y fácil de editar. A medida que escribas programas más complejos y bases de código más grandes, se recomienda utilizar métodos con mayor frecuencia para evitar confusiones. Practicar con métodos te convertirá en un programador realmente competente.

Otros tipos de retorno

Puedes utilizar cualquier tipo de dato como valor de retorno. En capítulos anteriores, ya hemos retornado un tipo int desde un método. También puedes retornar String, long, double o cualquier arreglo. Incluso podemos retornar un tipo definido por el usuario (clase) creado por nosotros.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 2. Capítulo 4

Pregunte a AI

expand

Pregunte a AI

ChatGPT

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

Awesome!

Completion rate improved to 2.63

bookVoid

Desliza para mostrar el menú

Cómo devolver nada en Java

Existe un caso especial cuando el tipo de retorno es void. Cuando el tipo de retorno es void, significa que no estamos devolviendo nada desde nuestro método. Simplemente realiza operaciones y no retorna un valor. Dicho método aún puede tener parámetros. Veamos un ejemplo de uso de un método void:

Main.java

Main.java

copy
1234567891011121314151617
package com.example; // do not modify the code below this comment public class Main { // method to print the string value passed as a parameter static void printStringValueFromParameter(String value) { System.out.println("Value from parameter: " + value); } public static void main(String[] args) { // creating a string variable to be passed as a parameter String string = "Hey, I'll be printed through a method!"; // calling the method and passing the string as a parameter printStringValueFromParameter(string); } }

Hemos escrito y utilizado un método que no devuelve nada. Este método void recibe un parámetro de tipo String y lo imprime en pantalla. Lo llamamos en el método main, y funciona correctamente.

Un método void también puede realizar operaciones más complejas sin devolver nada, como imprimir un arreglo. Será mucho más limpio cuando imprimamos un arreglo usando solo un método en el método main. Veamos un ejemplo de código:

Main.java

Main.java

copy
12345678910111213141516171819202122232425
package com.example; // do not modify the code below this comment public class Main { // method to print each element of an integer array to the console static void printIntArrayToTheConsole(int[] array) { // iterating over each element of the array and printing it for (int element : array) { System.out.print(element + " "); } // using an empty System.out.println to add a blank line in the console System.out.println(); } public static void main(String[] args) { // creating the first integer array int[] firstArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // creating the second integer array int[] secondArray = {0, 2, 4, 6, 8, 10, 12, 14, 16}; // calling the method to print both arrays printIntArrayToTheConsole(firstArray); printIntArrayToTheConsole(secondArray); } }

Como puedes ver, ahorramos líneas de código al escribir un método separado para imprimir el arreglo. En lugar de escribir repetidamente un nuevo ciclo for-each para imprimir el arreglo, simplemente llamamos a este método y pasamos el arreglo como parámetro.

De esta manera, podemos decir que los métodos mejoran considerablemente nuestro código. Lo hacen más legible y fácil de editar. A medida que escribas programas más complejos y bases de código más grandes, se recomienda utilizar métodos con mayor frecuencia para evitar confusiones. Practicar con métodos te convertirá en un programador realmente competente.

Otros tipos de retorno

Puedes utilizar cualquier tipo de dato como valor de retorno. En capítulos anteriores, ya hemos retornado un tipo int desde un método. También puedes retornar String, long, double o cualquier arreglo. Incluso podemos retornar un tipo definido por el usuario (clase) creado por nosotros.

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

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