Types of Methods in Java

Types Of Methods

There are two types of methods, i.e., pre-build and user-defined methods.

  • Pre Build Methods: Already created. We can use it. E.g., System.out.println(“Hello World”)
  • User Define Methods: We can create as per our requirements.

We Can Also Simplify Methods Types In The Following Ways

  • No Parameter No Return Type
  • Parameter and No Return Type
  • Parameter and Return Type
  • No Parameter and Return Type

No Parameter And No Return Type

public class Main {
    public static void main(String[] args) {
    printMyName();
}
public static  void printMyName(){
    System.out.println("My name is Bishworaj Poudel");
    }
}
            
Show Output

Parameter And No Return Type

public class Main {
    public static void main(String[] args) {
        findAgeFromBirthYear(1990);
    }
    //2. Parameter and No Return Type
    public static void findAgeFromBirthYear(int birthYear){
                int age = 2022 - birthYear;
                System.out.println("The age is "+age);
            }
        }
         
Show Output

Parameter And Return Type


public class Main {
    public static void main(String[] args) {
        int total = add(10,20);
        System.out.println(total);
            
    }
    //3. Parameter and Return Type
    public static int add(int n1, int n2){
        return  n1+n2;
        }
}
         

No Parameter And Return Type

public class Main {
    public static void main(String[] args) {
       int[] ages = {18, 17, 15, 19,32};
       int totalVoters = 0;
       int totalNonVoters = 0;
        for(int age: ages){
            if(age >= getVoterAge()){
                totalVoters = totalVoters + 1;
            }else {
                totalNonVoters = totalNonVoters+1;
            }
        }
        System.out.println("Total No of Voters: "+totalVoters);
        System.out.println("Total No of Non Voters: "+totalNonVoters);
    }

    public static int getVoterAge(){
        return 17;
    }
}
Show Output