Java - Class Method Definition

What is a method?

A method defines the behavior of the objects or class itself.

A method is a named block of code.

A method may accept input values from the caller and it may return a value to the caller.

The list of input values is called parameters.

A method may have zero parameters.

A method is defined inside the body of a class.

Syntax

The general syntax for a method declaration is of the form

<modifiers> <return type> methodName (parameters list) <throws clause> {
    // Body of the method
}
ItemMeaning
<modifiers> an optional list of modifiers
<return type> data type of the value returned from the method
methodNamethe name of the method.

Example

The following is an example of a method: it is named add.

It takes two parameters of type int named n1 and n2, and it returns their sum:

int add(int n1, int n2) {
   int sum = n1 + n2;
   return sum;
}

To call your add method, you need to use the following statement:

add(10, 12);

Demo

public class Main {
  public static void main(String[] args) {
    System.out.println(add(2, 4));
    System.out.println(add(3, 4));
    System.out.println(add(4, 4));
    System.out.println(add(5, 4));
  }//from  w  w w . ja  va 2s. c  o  m

  static int add(int n1, int n2) {
    int sum = n1 + n2;
    return sum;
  }
}

Result

Exercise