📦 Lesson 7: Java Methods (Modular Code)
⏱️ Estimated time: 30 minutes | Difficulty: Intermediate
Organization
Methods are blocks of code that only run when called. They help organize your program into logical, reusable parts.
Creating Methods
public class Methods {
// Method with no return value
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
// Method with return value
static int add(int a, int b) {
return a + b;
}
// Method with default-like behavior (overloading)
static double area(double radius) {
return Math.PI * radius * radius;
}
static double area(double width, double height) {
return width * height;
}
public static void main(String[] args) {
greet("Alice"); // Hello, Alice!
int sum = add(5, 3); // 8
System.out.println(area(5)); // Circle area: 78.53
System.out.println(area(4, 6)); // Rectangle area: 24.0
}
}
Method Overloading
Same method name, different parameter lists. Java picks the right one automatically!
static int multiply(int a, int b) { return a * b; }
static double multiply(double a, double b) { return a * b; }
static int multiply(int a, int b, int c) { return a * b * c; }
multiply(3, 4); // Calls int version → 12
multiply(2.5, 3.0); // Calls double version → 7.5
multiply(2, 3, 4); // Calls 3-arg version → 24
Varargs (Variable Arguments)
static int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
sum(1, 2); // 3
sum(1, 2, 3, 4, 5); // 15
✅ Quick Quiz
❓ What does 'void' mean as return type?
❓ What is method overloading?
❓ What does 'static' mean for methods?