Métodos Java (con ejemplos)

En este tutorial, aprenderemos sobre los métodos Java, cómo definir métodos y cómo usar métodos en programas Java con la ayuda de ejemplos.

Métodos Java

Un método es un bloque de código que realiza una tarea específica.

Suponga que necesita crear un programa para crear un círculo y colorearlo. Puede crear dos métodos para resolver este problema:

  • un método para dibujar el círculo
  • un método para colorear el círculo

Dividir un problema complejo en partes más pequeñas hace que su programa sea fácil de entender y reutilizable.

En Java, hay dos tipos de métodos:

  • Métodos definidos por el usuario : podemos crear nuestro propio método en función de nuestros requisitos.
  • Métodos de biblioteca estándar : estos son métodos integrados en Java que están disponibles para su uso.

Primero aprendamos sobre los métodos definidos por el usuario.

Declaración de un método Java

La sintaxis para declarar un método es:

 returnType methodName() ( // method body )

Aquí,

  • returnType : especifica qué tipo de valor devuelve un método. Por ejemplo, si un método tiene un inttipo de retorno, devuelve un valor entero.
    Si el método no devuelve un valor, su tipo de retorno es void.
  • methodName : es un identificador que se usa para hacer referencia al método particular en un programa.
  • cuerpo del método : incluye las instrucciones de programación que se utilizan para realizar algunas tareas. El cuerpo del método se incluye dentro de las llaves ( ).

Por ejemplo,

 int addNumbers() ( // code )

En el ejemplo anterior, el nombre del método es adddNumbers(). Y el tipo de retorno es int. Aprenderemos más sobre los tipos de devolución más adelante en este tutorial.

Esta es la sintaxis simple de declarar un método. Sin embargo, la sintaxis completa de declarar un método es

 modifier static returnType nameOfMethod (parameter1, parameter2,… ) ( // method body )

Aquí,

  • modificador : define los tipos de acceso si el método es público, privado, etc. Para obtener más información, visite Java Access Specifier.
  • static : si usamos la staticpalabra clave, se puede acceder sin crear objetos.
    Por ejemplo, el sqrt()método de la clase matemática estándar es estático. Por lo tanto, podemos llamar directamente Math.sqrt()sin crear una instancia de Mathclase.
  • parámetro1 / parámetro2 : estos son valores pasados ​​a un método. Podemos pasar cualquier número de argumentos a un método.

Llamar a un método en Java

En el ejemplo anterior, hemos declarado un método llamado addNumbers(). Ahora, para usar el método, necesitamos llamarlo.

Así es como podemos llamar al addNumbers()método.

 // calls the method addNumbers();
Funcionamiento de la llamada al método Java

Ejemplo 1: métodos Java

 class Main ( // create a method public int addNumbers(int a, int b) ( int sum = a + b; // return value return sum; ) public static void main(String() args) ( int num1 = 25; int num2 = 15; // create an object of Main Main obj = new Main(); // calling method int result = obj.addNumbers(num1, num2); System.out.println("Sum is: " + result); ) )

Salida

 La suma es: 40

En el ejemplo anterior, hemos creado un método llamado addNumbers(). El método toma dos parámetros ay b. Note la línea

 int result = obj.addNumbers(num1, num2);

Aquí, hemos llamado al método pasando dos argumentos num1 y num2. Dado que el método devuelve algún valor, hemos almacenado el valor en la variable de resultado.

Nota : el método no es estático. Por lo tanto, llamamos al método usando el objeto de la clase.

Tipo de retorno del método Java

Un método Java puede devolver o no un valor a la llamada a la función. Usamos la declaración de devolución para devolver cualquier valor. Por ejemplo,

 int addNumbers() (… return sum; )

Aquí, estamos devolviendo la variable suma. Dado que el tipo de retorno de la función es int. La variable suma debe ser de inttipo. De lo contrario, generará un error.

Ejemplo 2: Tipo de retorno de método

 class Main ( // create a method public static int square(int num) ( // return statement return num * num; ) public static void main(String() args) ( int result; // call the method // store returned value to result result = square(10); System.out.println("Squared value of 10 is: " + result); ) )

Salida :

 El valor al cuadrado de 10 es: 100

En el programa anterior, hemos creado un método llamado square(). El método toma un número como parámetro y devuelve el cuadrado del número.

Aquí, hemos mencionado el tipo de retorno del método como int. Por tanto, el método siempre debería devolver un valor entero.

Representación del método Java que devuelve un valor.

Note: If the method does not return any value, we use the void keyword as the return type of the method. For example,

 public void square(int a) ( int square = a * a; System.out.println("Square is: " + a); )

Method Parameters in Java

A method parameter is a value accepted by the method. As mentioned earlier, a method can also have any number of parameters. For example,

 // method with two parameters int addNumbers(int a, int b) ( // code ) // method with no parameter int addNumbers()( // code )

If a method is created with parameters, we need to pass the corresponding values while calling the method. For example,

 // calling the method with two parameters addNumbers(25, 15); // calling the method with no parameters addNumbers()

Example 3: Method Parameters

 class Main ( // method with no parameter public void display1() ( System.out.println("Method without parameter"); ) // method with single parameter public void display2(int a) ( System.out.println("Method with a single parameter: " + a); ) public static void main(String() args) ( // create an object of Main Main obj = new Main(); // calling method with no parameter obj.display1(); // calling method with the single parameter obj.display2(24); ) )

Output

 Method without parameter Method with a single parameter: 24

Here, the parameter of the method is int. Hence, if we pass any other data type instead of int, the compiler will throw an error. It is because Java is a strongly typed language.

Note: The argument 24 passed to the display2() method during the method call is called the actual argument.

The parameter num accepted by the method definition is known as a formal argument. We need to specify the type of formal arguments. And, the type of actual arguments and formal arguments should always match.

Standard Library Methods

The standard library methods are built-in methods in Java that are readily available for use. These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar) file with JVM and JRE.

For example,

  • print() is a method of java.io.PrintSteam. The print("… ") method prints the string inside quotation marks.
  • sqrt() is a method of Math class. It returns the square root of a number.

Here's a working example:

Example 4: Java Standard Library Method

 public class Main ( public static void main(String() args) ( // using the sqrt() method System.out.print("Square root of 4 is: " + Math.sqrt(4)); ) )

Output:

 Square root of 4 is: 2.0

To learn more about standard library methods, visit Java Library Methods.

What are the advantages of using methods?

1. The main advantage is code reusability. We can write a method once, and use it multiple times. We do not have to rewrite the entire code each time. Think of it as, "write once, reuse multiple times".

Example 5: Java Method for Code Reusability

 public class Main ( // method defined private static int getSquare(int x)( return x * x; ) public static void main(String() args) ( for (int i = 1; i <= 5; i++) ( // method call int result = getSquare(i); System.out.println("Square of " + i + " is: " + result); ) ) )

Output:

 Square of 1 is: 1 Square of 2 is: 4 Square of 3 is: 9 Square of 4 is: 16 Square of 5 is: 25

In the above program, we have created the method named getSquare() to calculate the square of a number. Here, the method is used to calculate the square of numbers less than 6.

Hence, the same method is used again and again.

2. Los métodos hacen que el código sea más legible y más fácil de depurar. Aquí, el getSquare()método mantiene el código para calcular el cuadrado en un bloque. Por lo tanto, lo hace más legible.

Articulos interesantes...