Java Methods With Examples
Define :
- Method first letter will always be in small case.
- A method is a collection of set of statements.
- As methods are always declared inside a class boundary hence, methods sometimes are called as member method, or member functions.
- We call functions as methods in java, or in other words In many languages (like C and C++), the term function is used to describe a named subroutine. The name that is more commonly used in Java is method.
Note - In Java, there are only classes, nothing exists outside a class. Although you can have public methods in non-public classes, You probably don't want that since the non-public classes will have limited visibility outside of the declaring class.
Syntax -
ReturnType methodName()
{
// Method body
}
|
- A method can hava different return types as shown below -
- void - It means the method will not have a returning value.
- int - It means the method has an integer type returning value.
- float - It means the method will have a floating type returning value.
- double - It means the method will have a double type returning value.
- Etc.
Static method -
- We can also declare static method by putting static keyword before return type of a method.
- A static method is invoked by - className methodName.
- We need static method so that their is no need to create class object to call method.
static ReturnType methodName()
{
// Method body
}
|
Method calling -
- In java a method can be called using methodName with opening, and closing parentheses with a semicolon in the end.
- A method can be called multiple times as well.
- We will understand method calling with an example as follows -
Example -
public class T{
int i =1;
static void show() {
System.out.println(++i);
}
public static void main(String[] args) {
show();
show();
show();
}
}
-----------------------------
Output -
2
3
4
|