Functions and Methods in Java

Methods or Functions

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 Code :

Run
import java.util.*;
public class Main{
    public static int prepInsta(int a){    //User defined Function
        a = a + 10;
        return a;
    }
    public static void main(String[] args){
        System.out.println(prepInsta(10));    //Pre-defined Function
    }
}
Methods in java

Components Of Method Declaration

There are several components that are used to declare a function/method in java.

  1. Access Modifiers : There are 4 types of access modifiers, Access modifiers helps to define the type of access of the function
    1. private
    2. public
    3. static
    4. protected
  2. 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.
  3. 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.
  4. 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.
  5. 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

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription