Lesson 13 of 20
Methods and Parameters
Organise code into reusable methods with parameters, return values, overloads, and clear responsibilities.
Learning objectives
- Declare and call a method.
- Pass information through parameters.
- Return a result to the caller.
- Understand the difference between
voidand value-returning methods. - Use method overloading appropriately.
1. Why use methods?
Methods break a large program into smaller named tasks. Good methods reduce duplication and make code easier to test and understand.
Example: a void method
public static void printWelcome() {
System.out.println("Welcome to the Student System");
}
public static void main(String[] args) {
printWelcome();
}
The method performs an action but returns no value, so its return type is void.
2. Parameters
Parameters allow the caller to supply values.
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
public static void main(String[] args) {
greet("Amina");
greet("Daniel");
}
3. Return values
public static double calculateTotal(double price, int quantity) {
return price * quantity;
}
public static void main(String[] args) {
double total = calculateTotal(19.90, 3);
System.out.printf("Total: RM %.2f%n", total);
}
4. Method overloading
Methods may share a name when their parameter lists differ.
public static int add(int a, int b) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
Mini project: reusable grade calculator
public class GradeCalculator {
public static String getGrade(int mark) {
if (mark >= 80) return "A";
if (mark >= 70) return "B";
if (mark >= 60) return "C";
if (mark >= 50) return "D";
return "F";
}
public static boolean isValidMark(int mark) {
return mark >= 0 && mark <= 100;
}
public static void main(String[] args) {
int mark = 76;
if (isValidMark(mark)) {
System.out.println("Grade: " + getGrade(mark));
} else {
System.out.println("Invalid mark.");
}
}
}
Common mistakes
| Problem | Why it happens | How to fix it |
|---|---|---|
| Missing return statement | A non-void method must return the declared type on every required path. | Return a value or change the method to void. |
| Arguments in wrong order | Parameters are positional. | Check the method signature and pass values in matching order. |
| One giant method | Too many responsibilities are mixed together. | Extract meaningful operations into smaller methods. |
Summary
Methods are the foundation of reusable program structure. In Lesson 14, you will place data and related methods together inside classes and create objects from those classes.