JAVA Theory
Methods in java:
A java method is a collection of statements that are grouped together to perform a specific operation.
Creating method:
Modifier
It defines the access type of the method. it has types of specifiers public, private, protected, default.
- 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 : Accessible within same class and package within which its class is defined.
Return type
The data type of the value returned by the method or void if does not return a value.
Method Name
The method consists of the name and the parameter list.
Parameter List
Comma separated list of the input parameters are defined, preceded with their data type, within the enclosed parenthesis. If there are no parameters, you must use empty parentheses ().
Method body
It must be enclosed within braces, all the codes for the method are written in it.
Example |
---|
public static int addition(int a, int b) { int sum; sum= a+b; //body of the method return sum; } |
Method signature:
It consists of the method name and parameter list. The return type and exception are not a part of the method signature.
Syntax |
---|
min (int a , int b)
|
Calling a method:
The method needs to be called for using its functionality. It is called in any of these three situations.
- It completes all the statements.
- An exception is thrown to it.
- It reaches a return statement.