Types of Methods in Java


A Java method is a collection of statements that are grouped together to perform an operation. A method in Java is a block of code that, when called, performs specific actions mentioned in it. For instance, if you have written instructions to draw a circle in the method, it will do that task.

You can insert values or parameters into methods, and they will only be executed when called. They are also referred to as functions. The primary uses of methods in Java are:

  • It allows code re-usability (define once and use multiple times)
  • You can break a complex program into smaller chunks of code
  • It increases code readability

 Two Types of Methods :
        1. User-defined Methods: We can create our own method based on our requirements.
        2. Standard Library Methods: These are built-in methods in Java that are available to use.

Syntax:
   Access_ specifier Return_type Method_name ( Parameter list )
   {
        // body of method ;
   }

 Access specifier :

  • Public : You can access it from any class
  • Private : You can access it within the class where it is defined
  • Protected : Accessible only in the same package or other subclasses in another package

 Return type :

  • Int : Int as the return type if the method returns value.
  • Void : Void as the return type if the method returns no value.

 Parameter list :

  • It is a list of arguments (data_type variable_name) that will be used in the method.

 Method body :

  • This is the set of instructions enclosed within curly brackets.

Source Code

class Methods {
    //No Return W/o args
    public void add() {
        int a = 123;
        int b = 10;
        System.out.println("Addition : " + (a + b));
    }
 
    //No Return With Args
    public void sub(int x, int y) {
        System.out.println("Subtraction : " + (x - y));
    }
    //Return Without Args
    public int mul() {
        int a = 123;
        int b = 10;
        return a * b;
    }
 
    //Return With Args
    public float div(int x, int y) {
        return (x / y);
    }
 
    //Recursion Function
    public  int factorial(int n)//5!  =1*2*3*4*5=120
    {
        if(n==1)
            return 1;
        else
            return (n*factorial(n-1));
    }
    /*
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
 
return 1;
return 2*1;
return 3*2;
return 4*6;
return 5*24;
 
 
* */
 
}
 
 
//Type of User Define Methods in Java
public class functions {
    public static void main(String args[]) {
        Methods o = new Methods();
        o.add();
        o.sub(123, 10);
        System.out.println("Muli : "+o.mul());
        System.out.println("Division : "+o.div(123,10));
    }
}
 

Output

Addition : 133
Subtraction : 113
Muli : 1230
Division : 12.0
To download raw file Click Here

Basic Programs