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.
The general syntax for a method declaration is of the form
<modifiers> <return type> methodName (parameters list) <throws clause> { // Body of the method }
Item | Meaning |
---|---|
<modifiers> | an optional list of modifiers |
<return type> | data type of the value returned from the method |
methodName | the name of the method. |
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);
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)); }// w w w . ja va2 s.com static int add(int n1, int n2) { int sum = n1 + n2; return sum; } }