Java Methods – Complete Guide
This page introduces the foundation of methods in Java — how they work, why they are essential, and how they help build reusable, modular, and efficient programs.
1. Introduction to Methods
A method in Java is a block of code designed to perform a specific task. Methods improve code reuse, readability, and organization.
class Demo {
void greet() {
System.out.println("Welcome to JavaHub!");
}
}
public class Test {
public static void main(String[] args) {
Demo d = new Demo();
d.greet();
}
}
Output:
Welcome to JavaHub!
2. Defining Methods
A method definition includes return type, name, parameters, and body.
int add(int a, int b) {
return a + b;
}
3. Overloaded Methods
Method overloading allows multiple methods with the same name but different parameter lists.
class Calc {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
}
4. Class Objects as Parameters
Objects can be passed as arguments, enabling collaboration between classes.
class Car {
int speed;
Car(int s){ speed=s; }
}
class Display {
void show(Car c){ System.out.println(c.speed); }
}
5. Access Control in Methods
Java provides access modifiers to control method visibility.
- public – accessible everywhere
- private – accessible only within the class
- protected – accessible within package + subclasses
- default – accessible only within package
6. Recursive Methods
Recursion is when a method calls itself until a base condition is met.
int fact(int n) {
if(n==1) return 1;
return n * fact(n-1);
}
Practice Questions – Click to Reveal Answers
1️⃣ What is a method?
A block of code that performs a task and can be reused.
2️⃣ What is method overloading?
Multiple methods with the same name but different parameters.
3️⃣ Define recursion.
A technique where a method calls itself.
Quick Summary
- Methods bring reusability and structure.
- Overloading offers flexibility in method usage.
- Objects can be passed as parameters.
- Access control defines method visibility.
- Recursion simplifies repetitive problems.