Lesson 14: Defining and Calling Methods
Methods define the behaviors or actions that an object can perform.
1. Method Structure (Signature)
A method signature consists of the method name and the type and number of its parameters. The full declaration also includes access modifiers, return type, and body.
Structure: AccessModifier Static/Non-Static ReturnType MethodName(Parameter List) { // Body }
java public class Calculator {
// Method 1: No parameters, returns nothing (void)
public void printWelcome() {
System.out.println("Welcome to the Calculator");
}
// Method 2: Takes two int parameters, returns an int
public int add(int num1, int num2) {
int result = num1 + num2;
return result; // Must return a value matching the return type (int)
}
}
2. The return Keyword
- If a method has a return type (e.g.,
int,String,Dog), it must usereturnto send a value back to the caller. - If the method returns
void,returnis optional (used only to exit the method early).
3. Calling Methods
To call a non-static method, you must first create an instance (object) of the class.
java Calculator calc = new Calculator();
// Calling a void method calc.printWelcome();
// Calling a method that returns a value int sum = calc.add(15, 7); System.out.println("The sum is: " + sum); // Output: 22
Note: If a method is declared static, you call it directly using the Class name (e.g., Calculator.addStatic(...)), without needing an object instance.