1) What is Method?
In Java, a method is a block of code that performs a specific task and only runs when it is called.
Methods are used to define the behavior of objects and classes, allowing you to reuse code without retyping it.
Java categorizes methods into two primary types:
Predefined (Standard Library) Methods: Built-in methods provided by Java libraries, such as System.out.println() or Math.sqrt().
User-defined Methods: Custom blocks of code written by programmers to solve specific problems.
2) What is Method Overloading?
Method overloading in Java is a feature that allows a class to have multiple methods with the same name, provided they have different parameter lists.
It is a form of compile-time polymorphism (also known as static binding), where the Java compiler determines which method to call based on the arguments provided.
3) Core Rules for Overloading
To successfully overload a method, the method signature (name + parameters) must be unique. Methods can be overloaded by changing:
Number of Parameters: For example,
add(int a, int b)andadd(int a, int b, int c).Data Types of Parameters: For example,
display(int a)anddisplay(String a).Order of Parameters: For example,
process(int a, String b)andprocess(String b, int a).
Example:
public class Calc {
public static void main(String[] args) {
Calc obj = new Calc();
System.out.println(obj.add(10, 20)); // Method 1
System.out.println(obj.add(10, 20, 30)); // Method 2
System.out.println(obj.add(10.5, 20.5)); // Method 3
}
// Method 1: Two integers
public int add(int a, int b) {
return a + b;
}
// Method 2: Three integers
public int add(int a, int b, int c) {
return a + b + c;
}
// Method 3: Double values
public double add(double a, double b) {
return a + b;
}
}
Output:

Top comments (0)