Java Methods

 

Java Methods

Methods or Functions are a block of code that accept certain parameters and perform actions whenever they are called. Methods are always written inside a java class and can be called by simply referring to the method name.

 

Passing Parameters:

Parameters are nothing but the variables that are passed inside the parenthesis of a method. We can pass a single or more than one parameter of different datatypes inside our method.


Example 1: Passing single parameter


public class MethodExample {

    static void Details(String name) {
        System.out.println("Welcome " + name);
    }
    
    public static void main(String[] args) {
        Details("Maxon");
    }
}


Output:

Welcome Maxon


Example 2: Passing multiple parameters


public class MethodExample {

    static void Details(String name, int roll) {
        System.out.println("Welcome " + name);
        System.out.println("Your roll number is "+ roll);
    }
    
    public static void main(String[] args) {
        Details("Maxon", 423101);
    }
}


Output:

Welcome Maxon
Your roll number is 423101


Example 3: Method with loop


public class MethodIf {
    static int Details(int num) {
        int fact = 1;
        for (int i=2; i<=num; i++) {
            fact = fact * i;
        }
        return fact;
    }
    
    public static void main(String[] args) {
        System.out.println(Details(3));
        System.out.println(Details(4));
        System.out.println(Details(5));
    }
}


Output:

6
24
120


Example 4: Method with control statements


public class Methodloop {
    static void Details(int marks) {
        if (marks < 35) {
            System.out.println("Fail");
        } else if (marks >= 35 && marks < 65) {
            System.out.println("B grade");
        } else if (marks >= 65 && marks < 75) {
            System.out.println("A grade");
        } else if (marks >= 75 && marks < 100) {
            System.out.println("O grade");
        } else {
            System.out.println("Invalid marks entered");
        } 
    }
    
    public static void main(String[] args) {
        Details(25);
        Details(90);
        Details(60);
    }
}


Output:

Fail
O grade
B grade


So what can we make out from e.g.3 and e.g.4? In e.g.3, we have created a method without using the void keyword, this lets us return the value inside the method. Whereas in e.g.4, we have created a method using void keyword, this means that our method wont return a value.