Methods
A method is a collection of statements that perform some specific task and return result to the caller.
Methods allow us to reuse the code without retyping the code.
In general, method declarations has six components :
- Modifier:
Defines access type of the method.
Java has four types of the access specifiers:
public
:
Accessible in all class in your application
protected
:
Accessible within the class in which it is defined and in its subclass(es)
private
:
Accessible only within the class in which it is defined
- default (declared/defined without using any modifier):
Accessible within the same class and package within which the class is defined
- The return type:
The data type of the value returned by the method or
void
if does not return a value
- Method name:
The rules for field names apply to method names as well, but the convention is a little bit different.
- Parameter list:
Comma-separated list of the input parameters is given, preceded with their data types, within the enclosed parentheses.
- Exception list:
The exceptions that you expect the method will throw.
- Method body:
It is enclosed between braces.
It includes the code needed to be executed to perform your intended operations.