he Concept: The "Black Box"
A method is a self-contained block of code that performs a specific task. Imagine a Toaster.
Input: You put in bread (this is called a Parameter).
Action: The toaster heats it up (the Logic).
Output: It pops out toast (the Return Value).
You don't need to know how the toaster works every time; you just need to know what to give it and what you’ll get back.
The Anatomy of a Method
A standard method looks like this: public static returnType methodName(parameters) { ... }
returnType: What kind of data comes out? If nothing comes out, we usevoid. If a number comes out, we useint.methodName: The name we use to call it (e.g.,calculateTax).parameters: The inputs the method needs to do its job.returnkeyword: This sends the final result back to whoever called the method.
The Code Example:
public class MethodsDemo {
// 1. A method that takes two numbers and RETURNS their sum
// It is 'static' so we can call it directly from main
public static int addNumbers(int a, int b) {
int result = a + b;
return result; // Sending the answer back
}
// 2. A method that takes a String and returns NOTHING (void)
// It just performs an action (printing)
public static void greetUser(String name) {
System.out.println("Hello, " + name + "! Welcome to Topic 6.");
}
public static void main(String[] args) {
// Calling the greeting method
greetUser("Alice");
greetUser("Bob");
// Calling the math method and storing the result in a variable
int total = addNumbers(25, 75);
System.out.println("The sum of 25 and 75 is: " + total);
// We can also call it directly inside a print statement
System.out.println("Quick Math (5+5): " + addNumbers(5, 5));
}
}Expected Output:
Hello, Alice! Welcome to Topic 6.
Hello, Bob! Welcome to Topic 6.
The sum of 25 and 75 is: 100
Quick Math (5+5): 10Methods are the foundation of DRY (Don't Repeat Yourself) programming.
Organization: Your code is easier to read.
Reusability: Write once, use a million times.
Debugging: If the math is wrong, you only have to fix it in one place (the method), not in fifty different places throughout your app.
Pro Tip: In Java, we use camelCase for method names (e.g.,
calculateFinalScore). It starts with a lowercase letter, and every word after starts with an uppercase letter.