DEV Community

Cover image for Java Methods
Karthick (k)
Karthick (k)

Posted on

Java Methods

Java Methods are blocks of code that perform a specific task. A method allows us to reuse code, improving both efficiency and organisation. All methods in Java must belong to a class. Methods are similar to functions and expose the behaviour of objects.

A method allows us to write a piece of logic once and reuse it wherever needed in the program.
This helps keep your code clean, organised, easier to understand and manage.

Passing Parameters:
Parameters are nothing but the variables that are passed inside the parentheses of a method. We can pass a single or more parameters of different data types inside our method.

Example 1: Passing a single parameter

public class MethodExample {

    static void Details(String name) {
        System.out.println("Welcome " + name);
    }

    public static void main(String[] args) {
        Details("Mitali");
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome Mitali

Method Overloading

Method Overloading is when we create multiple methods with the same name but pass different types of parameters inside it. This allows us to overload the same method many times. We only need to pass a different type or a different number of parameters inside it.

Example:

public class MethodOverloadEx {
    static void Details(String name, int marks) {
        System. out.println("Welcome " + name);
        System. out.println("Your got "+ marks + " marks in exam.");
    }

    static void Details(String name, double marks) {
        System.out.println("Welcome " + name);
        System.out.println("Your got "+ marks + " marks in exam.");
    }

    public static void main(String[] args) {
        Details("Ridhi", 89);
        Details("Ritesh", 93.5);
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Welcome, Ridhi
You scored 89 marks in the exam.
Welcome, Ritesh
You scored 93.5 marks in the exam.

Top comments (0)