Functions and Methods in Java
What is Methods in Java
The Methods is also known as functions in java. Functions are the building blocks of our code which are called for some specific purposes. Data can be passed through these methods which is known as parameters.
Functions are the collection of statements within a block which is called only when it is needed. It is mainly used to reuse a specific code in your program.
Creating a Method:
Methods or Functions in Java is created within a class and is declared by its name and followed by Parameters that is being passes in a Function.
There are two types of methods that we use in Java:
- Pre-defined Methods
- User defined Methods
Example:
import java.util.*; public class Main{ //User defined Function public static int prepInsta(int a){ a = a + 10; return a; } public static void main(String[] args){ //Pre-defined Function System.out.println(prepInsta(10)); } }
Output: 20
Components Of Method Declaration:
There are several components that are used to declare a function/method in java.
- Access Modifiers : There are 4 types of access modifiers, Access modifiers helps to define the type of access of the function
- private
- public
- static
- protected
- Return Type : it helps to determine the return value of the methods it can be int, char or long according to the need of the program. It can be void it the program isn’t returning any value.
- Method Name : Correctly Naming your methods is more important as it’ll be more convenient for the programmer to analyze your program and for the debugging processes.
- Parameters : It is used to pass input parameter from the main function to our methods, methods should be enclosed with brackets if there is no variable available as parameter.
- Method Body : It is enclosed by open and close brackets. It contains all the operations that is to be performed by the method.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment