How to define a method in Java?

In Java, a method is a block of code used to perform a specific task. You can define a method using the following syntax:

Modifiers Return type Method name(Parameter list) {
// Method body
}

  1. Modifiers: specify the access permissions of a method, which can be public, private, protected, or default (no modifier).
  2. Return type: The data type that the method returns can be either a built-in Java data type or a custom class or interface.
  3. Method name: Name of the method that follows the naming rules of Java identifiers.
  4. Parameter list: Specifies the parameters accepted by the method, which can be zero or more, separated by commas.
  5. Method body: comprises the block of code to be executed.

For example, here is a definition of a method that calculates the sum of two integers:

public int calculateSum(int num1, int num2) {
    int sum = num1 + num2;
    return sum;
}

In the example above, there is a method named calculateSum that returns an integer and takes two integer parameters, num1 and num2. The code inside the method calculates the sum of num1 and num2 and returns the result.

bannerAds