A method is a block of code which only runs when it is called.
You can pass data, known as parameters, into a method.
Methods are used to perform certain actions, and they are also known as functions.
Why use methods? To reuse code: define the code once, and use it many times.
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by parentheses (). Java provides some pre-defined methods, such as System.out.println().

Call a Method
To call a method in Java, write the method’s name followed by two parentheses () and a semicolon;
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}
}
Types of Method
There are two types of methods in Java:
- Predefined Method
- User-defined Method
Predefined Method :
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc.
System.out.println().
User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement.
Method Overloading
Method overloading is a feature in Java that allows multiple methods with the same name but different parameter lists to exist within the same class. It enhances the flexibility and readability of the code.
Example :
public class PrintUtil {
public void print(String message) {
System.out.println(message);
}
public void print(String message, int times) {
for (int i = 0; i < times; i++) {
System.out.println(message);
}
}
}
Method Overriding
Method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. It is a key aspect of polymorphism in Java, allowing subclasses to customize or extend the behavior of inherited methods.
Example :
class Animal {
public void sound() {
System.out.println(“Animal makes a sound”);
}
}
class Dog extends Animal {
public void sound() {
System.out.println(“Dog barks”);
}
}