Module 4: Methods and Code Reusability
Lesson focusDefining and Calling Methods
Learn how to define your own methods to create reusable blocks of code, making your programs more organized and easier to maintain.
What is a Method? A method is a block of code that performs a specific task. It runs only when it is called. You can pass data, known as parameters, into a method.
Why Use Methods?
- Reusability: Write the code once and use it many times.
- Organization: Break down complex problems into smaller, manageable pieces.
- Readability: Well-named methods make your code easier to understand.
Anatomy of a Method Definition:
- Access Modifier: (e.g.,
public) - Who can call this method?
static(optional): If present, the method belongs to the class, not an object.
- Return Type: The data type of the value the method returns (e.g.,
int,String, orvoidif it returns nothing).
- Method Name: A descriptive name for the method (e.g.,
calculateSum).
- Parameters: A list of variables passed into the method, enclosed in parentheses
().
- Method Body: The code to be executed, enclosed in curly braces
{}.
Calling a Method: To execute a method, you simply write its name followed by parentheses, providing any required arguments: int sum = calculateSum(10, 20);
The return Keyword: If a method has a return type other than void, its body must end with a return statement that provides a value of that type.
Mini-Exercise: Create a method named greetUser that takes a String (a name) as a parameter and prints a personalized greeting, like "Hello, [Name]!". Call this method from your main method with your name.
public class Calculator {
public static void main(String[] args) {
// Call the add method and store the result
int result = add(5, 10);
System.out.println("The sum is: " + result); // The sum is: 15
}
// Method definition
public static int add(int num1, int num2) {
int sum = num1 + num2;
return sum; // Return the result
}
}