Types of Methods in Java Programming
A method in Java is a block of code containing some statements' collections. This collection of statements forms a method that performs a specific task or operation. Methods are also sometimes referred to as functions.
Some important points about methods in Java are mentioned below.
- It is a collection of statements.
- A method, once defined, can be used multiple times. Hence, it increases code readability and reusability.
- A method in Java should be present inside the class.
- Complex operations can be broken inside methods for computation.
- The main() method is the most important example of a method in Java, as it is the entry point for any program.
Syntax
<access_specifier> <return_type> <method_name>( parameters)
{
//method body
}
Types of Methods
The methods in Java are divided into two types:
- Pre-defined Method
- User-defined Method.
1. Pre-defined Method
As the name suggests, the predefined methods are the methods that are already defined in the Java library. It can also be referred to as a standard library or built-in method. They do not need to be redefined in the program. The pre-defined method can be easily utilized anytime or anywhere in the program using a method call. When any predefined method is called, some collection of statements related to the respective method gets executed in the background that is already present in the Java class library.
Some examples of the pre–defined methods in Java are sqrt(), max(), min(), print(), length(), hashCode(), and toString().
Now, go through the example below, where we have used some pre–defined computation methods.
FileName: PredefinedMethods.java
public class PredefinedMethods {
// Main method
public static void main(String[] args) {
int n1 = 10;
int n2 = 20;
// Print using Predefined Methods
System.out.println("The max value between " +n1 +" and " +n2 +" is " +Math.max( n1, n2));
System.out.println("The min value between " +n1 +" and " +n2 +" is " +Math.min( n1, n2));
System.out.println(Math.sqrt(n1));
}
}
Output:
The max between 10 and 20 is 20
The min between 10 and 20 is 10
3.1622776601683795
2. User-defined Method
The method defined by the developer or User and not defined in the Java class library is called the User-defined Method. The User–defined methods can be modified according to the need or requirement.
In the example below, we have defined 4 methods that are add(), subtract(), multiply(), and divide(), which are user-defined. After defining the method, we made a method call in the main() method to get and print the results from the methods.
FileName: UserDefinedMethod.java
public class UserDefinedMethod {
//User-defined Method: 1
static int add( int a, int b) {
int result = a + b;
return result;
}
//User-defined Method: 2
static int subtract( int a, int b) {
int result = a - b;
return result;
}
//User-defined Method: 3
static int muliply( int a, int b) {
int result = a * b;
return result;
}
//User defined Method: 4
static int divide( int a, int b) {
int result = a / b;
return result;
}
// Main method
public static void main(String[] args) {
int a = 20;
int b = 10;
// Method call and Print the Result
System.out.println(a +" + " +b +" = " +UserDefinedMethod.add( a, b));
System.out.println(a +" - " +b +" = " +UserDefinedMethod.subtract( a, b));
System.out.println(a +" * " +b +" = " +UserDefinedMethod.muliply( a, b));
System.out.println(a +" / " +b +" = " +UserDefinedMethod.divide( a, b));
}
}
Output:
20 + 10 = 30
20 - 10 = 10
20 * 10 = 200
20 / 10 = 2
The Methods in Java can also be further divided into the following types.
- Instance Method
- Static Method
- Abstract method
- Factory Method.
a) Instance Method
In Java, the instance method is a static method owned by the class and its instance. To make a method call for an instance, creating an instance of that class is necessary.
Syntax
<return_type> <method_name>( parameters );
Now, observe the below program, which checks for even or odd.
FileName: InstanceMethod.java
public class InstanceMethod {
// Instance Method
public void checkEvenOrOdd( int num) {
if (num % 2 == 0) {
System.out.println("The number " +num + " is Even");
}
else {
System.out.println("The " +num + " is Odd");
}
}
// Main method
public static void main(String[] args) {
int num = 12;
// Create Intsnace of the class
InstanceMethod instanceMethod = new InstanceMethod();
// Method call and Print the Result
instanceMethod.checkEvenOrOdd(num);
}
}
Output 1:
The number 12 is Even
Output 2: When num = 13
The 13 is Odd
Output 3: When num = 8
The number 8 is Even
There exist 2 types of Instance Method.
Accessor Method: The method that reads the value of the instance variable is referred to as the accessor method. It is sometimes also called as getters in Java. The accessor method can be easily known as they are prefixed with the word ‘get’. The accessor method is used for returning a private field value.
public String getName() {
return name;
}
Mutator Method: The method that reads and modifies the instance variable's value is called the mutator method. It is sometimes also called as setters or modifiers in Java. The mutator method can be easily known as they are prefixed with the word ‘set’. The mutator method is used when we need to set a private field value.
public void setName(String name) {
this.name = name;
}
Example
The below example demonstrates the usage of accessor and mutator methods in Java.
FileName: AccessorAndMutator.java
class Employee {
private String name;
private String empID;
private double salary;
// Accessor Method: 1
public String getName() {
return name;
}
// Mutator Method: 1
public void setName(String name) {
this.name = name;
}
// Accessor Method: 2
public String getEmpID() {
return empID;
}
// Mutator Method: 2
public void setEmpID(String empID) {
this.empID = empID;
}
// Accessor Method: 3
public double getSalary() {
return salary;
}
// Mutator Method: 3
public void setSalary(double salary) {
this.salary = salary;
}
public void display() {
System.out.println("Name is "+name);
System.out.println("Employee ID is "+empID);
System.out.println("The salary is "+salary);
}
}
public class AccessorAndMutator {
// Main method
public static void main(String[] args) {
Employee employee = new Employee();
// modify the fields
employee.setName("Ranjan");
employee.setEmpID("FE23221");
employee.setSalary(20000);
employee.display();
}
}
Output:
Name is Ranjan
Employee ID is FE23221
The salary is 20000.0
b) Static Method
The static method is created using the 'static' keyword and it does not need to create an instance of the class for its method call. The static method belongs to the class rather than the instance of the class. It is invoked directly using the class Name.
Syntax
static <return_type> <method_name>( parameters );
FileName: StaticMethod.java
public class StaticMethod {
// Static method to check for prime number
static void primeCheck(int num) {
// Holds the count of values
int count = 0;
// 0 and 1 are not a prime number
if (num == 0 || num == 1) {
System.out.println("The number is not prime");
return;
}
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
count++;
}
}
// If the number of factors is greater than 1,
//The number is not prime.
if (count > 1) {
System.out.println("The number " +num + " is not prime");
}
else {
System.out.println("The number " +num + " is prime");
}
}
// Main method
public static void main(String[] args) {
// Input number
int num = 7;
// Method call
StaticMethod.primeCheck(num);
}
}
Output 1:
The number 7 is prime
Output 2: When num = 14
The number 14 is not prime
Output 3: When num = 17
The number 17 is prime
c) Abstract Method
In Java, the Abstract methods are the methods that do not provide any implementation during their declaration. It does not contain a body. The ‘abstract’ keyword is used to declare a method as abstract. Note that its class should also be declared as abstract to declare an abstract method.
Syntax
abstract void <method_name>();
FileName: AbstractMethodExample.java
// Abstract class
abstract class Example //abstract class
{
//abstract method declaration
abstract void message();
}
// Main class
public class AbstractMethodExample extends Example
{
// abstract method implementation
void message()
{
System.out.println("Inside the Abstract method");
}
// Main method
public static void main(String args[])
{
// Create an instance of the Abstract class
Example example = new AbstractMethodExample();
// abstract method call
example.message();
}
}
Output:
Inside the Abstract method
d) Factory Method
In Java, the Factory methods are the methods that return an object to the class to which it belongs. All the static methods in Java are factory methods. For example, NumberFormat obj = NumberFormat.getNumberInstance();