Methods in Java

It is a collection of statement which is used to perform some operation. The main benefit to use method is that it provides code reusability. Once a method is created, then it can be reused multiple times as per requirements.

Creating Method

To create a method following syntax is used:

Access_modifier Return_type Method_name (Parameter_list) {
//Body of method
}

Where,
Access_modifier: It defines the access type of methods like private, public, protected.
Return_type: Specify the return type of method.
Method_name: It shows the name of method.
Parameter _list: Contains a list of parameters with their type. A method contains either zero parameter or more than 0 parameters.

Learn Java

Body of method:

Contains the statements which perform some operation.

Example:

public static int sum(int i, int j) {
int total;
total = i + j;
return total;
}

To call the method following syntax is used:

Method_name(Parameter_list);

Example:

public class Intellipaat{
public static void main(String[] args) {
int a = 10;
int b = 20;
int c = sum(a, b);
System.out.println("Sum of two numbers = " + c);
}
public static int sum(int i, int j) {
int total;
total = i + j;
return total;
}
}

Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!

Course Schedule

Name Date Details
Python Course 01 Apr 2023(Sat-Sun) Weekend Batch
View Details
Python Course 08 Apr 2023(Sat-Sun) Weekend Batch
View Details
Python Course 15 Apr 2023(Sat-Sun) Weekend Batch
View Details

Leave a Reply

Your email address will not be published. Required fields are marked *