Definition and declaration

The definition of a function specifies exactly how a function is constructed, what parameters are passed to it, and what value it returns to the calling function.

With the declaration we name a variable and make it known to the compiler.

Definition and declaration differ in some points. The definition includes a memory allocation for the methods, while no memory is allocated in the declaration. The declaration can be done several times, vice versa a method can be defined exactly once in a program.

Methods must be declared within a class in java. This gives the methods access to all variables of the object.

Syntax

modifiers return_type method_name(type parameter_1, type parameter_2, ...) {
	// code to be executed
}

Example

private void print() {
	// code to be executed 
}

Another Example

Code Explanation

LineDescription
1Defines the method add() with the input parameters a and b of type integer.
It’s a static, public method. Static methods can be called via a class and it is not necessary to create an object each time. A public method can also be called outside the class in which it was declared. The return value of the method is of type integer.
2Creates a variable named result of type integer
3Assigns the sum of a and b to the variable result
4Returns the variable result
public static int add(int a, int b) {
	int result;
	result = a + b;
	return result;
}