Methods: Building Reusable Blocks of Code
As your programs get bigger, writing everything inside the main method becomes messy and hard to manage. Methods allow you to group a block of code together, give it a name, and run it whenever you need it.
Think of a method like a recipe: you define the steps once, and you can "cook" it as many times as you want.
1. Anatomy of a Method
A basic method consists of a header and a body.
public static int addNumbers(int a, int b) {
// Body: The code to execute
int sum = a + b;
return sum;
}
The Breakdown:
public static: For now, we use these keywords so we can call the method directly from ourmainclass.- Return Type (
int): This tells Java what kind of data the method gives back. If it gives nothing back, we usevoid. - Method Name (
addNumbers): UsecamelCaseto describe what the method does. - Parameters (
int a, int b): These are inputs the method needs to do its job. return: This keyword sends the result back to whoever called the method.
2. Calling a Method
Once a method is defined, you "call" it by using its name followed by parentheses.
public class Main {
public static void main(String[] args) {
// Calling the method and storing the result
int result = addNumbers(5, 10);
System.out.println("The sum is: " + result);
}
public static int addNumbers(int a, int b) {
return a + b;
}
}
3. Void Methods (No Return)
Sometimes you just want a method to perform an action (like printing text) without sending a value back. For this, we use the void return type.
public static void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
// Called as: sayHello("Ahmed");
4. Why Use Methods?
- DRY (Don't Repeat Yourself): Instead of writing the same logic 10 times, write one method and call it 10 times.
- Readability: It’s easier to read
calculateTax()than 20 lines of math. - Maintainability: If you need to change how the tax is calculated, you only have to change it in one place.
💻 Full Practical Example: The Area Calculator
Copy this code to see how different methods can be used together:
import java.util.Scanner;
public class Geometry {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
displayWelcome();
System.out.print("Enter the radius of your circle: ");
double r = input.nextDouble();
double area = calculateArea(r);
System.out.printf("The total area is: %.2f %n", area);
input.close();
}
// A void method with no parameters
public static void displayWelcome() {
System.out.println("Welcome to the Geometry Tool!");
System.out.println("----------------------------");
}
// A method that takes a double and returns a double
public static double calculateArea(double radius) {
return Math.PI * Math.pow(radius, 2);
}
}
💡 Challenge: The Temperature Pro
Create a program with two methods:
toCelsius(double fahrenheit): Returns the converted temperature.checkWeather(double celsius): A void method that prints "Cold" if the temp is below 15, and "Warm" if it's 15 or higher.
Call both from your main method!