Method Rules and Best Practices in Java
Methods follow some basic rules in Java. Using clear names and keeping a method focused on one task makes your programs easier to read, test, and maintain.
Rules for Declaring Methods
A method must be declared inside a class and must have a valid return type, name, parameter list, and body.
Example 1: A Valid Method Declaration
class MethodRulesDemo {
// Method name uses camelCase
static int calculateTotal(int price, int quantity) {
return price * quantity;
}
public static void main(String[] args) {
System.out.println(calculateTotal(50, 3));
}
}
Output:
150
Explanation:
intis the return type, so this method must return an integer.calculateTotalis a meaningful camelCase method name.priceandquantityare parameters inside the parentheses.
Important Method Rules
- A method must be declared inside a class.
- The number, types, and order of arguments in a call must match the method parameters.
- A method with a non-
voidreturn type must return a matching value. - A
voidmethod cannot return a value. - Overloaded methods must have different parameter lists.
Example 2: Matching Arguments with Parameters
class MethodRulesDemo {
static void displayAge(String name, int age) {
System.out.println(name + " is " + age + " years old.");
}
public static void main(String[] args) {
displayAge("Simran", 24);
}
}
Output:
Simran is 24 years old.
Explanation:
The first argument is a String for name, and the second is an int for age. Their number, types, and order match the parameters.
Best Practices
These habits make methods easier to understand and reuse.
- Use a meaningful name, such as
calculateTotal()ordisplayMessage(). - Keep one method focused on one clear task.
- Use parameters instead of relying on fixed values inside a method.
- Break a long or complex task into smaller methods.
- Choose a return type that matches the result the method should provide.
Example 3: One Method, One Task
class MethodRulesDemo {
static void displayWelcomeMessage() {
System.out.println("Welcome to ShikshaSanchar");
}
public static void main(String[] args) {
displayWelcomeMessage();
}
}
Output:
Welcome to ShikshaSanchar
Explanation:
The name displayWelcomeMessage() clearly says what the method does. It performs one simple task: displaying a welcome message.
Chapter Summary:
- Methods organize code into reusable blocks.
- Parameters receive input and arguments supply input.
- Return types determine what a method can return.
- Method overloading uses one name with different parameter lists.
- Clear names and focused methods make programs easier to understand.