Java Calling a Method

Java Calling a Method

To call a method in Java, simply use the method name followed by parentheses and, if necessary, pass the arguments between parentheses. Here is an example of how to call a simple method:

public class Main {
  public static void main(String[] args) {
    // Calls method prints Message
    printsMessage();
  }

  public static void printsMessage() {
    System.out.println("Hello world!");
  }
}
S‮o‬urce:www.lautturi.com

In this example, the 'Main' class has a 'main' method that is the entry point of the application and a 'printsMessage' method. The 'main' method calls the 'printsMessage' method using the method name and the method runs, printing the message "Hello world!".

Here is an example of how to call a method that receives arguments:

public class Main {
  public static void main(String[] args) {
    // Calls the sum method with arguments 10 and 20
    int resultado = soma(10, 20);

    // Prints the result
    System.out.println(resultado);  // Prints: 30
  }

  public static int soma(int a, int b) {
    return a + b;
  }
}

In this example, the 'sum' method receives two arguments of the integer type and returns the sum of them. The 'main' method calls the 'sum' method by passing arguments 10 and 20 and stores the result in a 'result' variable. Finally, the 'main' method prints the result.

Note that to call a method, you must have access to it (that is, the method must be public or be in the same package), and the method must have the correct signature (that is, the name, the return type, and the types of the arguments must match the method declaration). Additionally, you must import the class that contains the method if it is in a different package using the 'import' declaration.

Created Time:2017-11-03 00:14:37  Author:lautturi