What Are Methods in Java?
A method is a reusable block of code that executes a specific task when called. Methods make programs modular and improve readability and maintainability. In Java, every method is part of a class.
Syntax of a Method
returnType methodName(parameters) {
// Method body
}
Parts of a Method
- Return Type: Specifies the type of value the method returns (e.g., int, void, String). If the method does not return any value, use void.
- Method Name: A unique name that identifies the method (e.g., calculateSum, display).
- Parameters: Inputs passed to the method, enclosed in parentheses (e.g., (int a, int b)).
- Method Body: Contains the logic or statements the method executes.
- Modifiers: Define the behavior of the method, such as public, private, static.
Types of Methods in Java
- Instance Methods
- Belong to an object.
- Can access instance attributes and other instance methods directly.
- Require an object of the class to invoke them.
- Static Methods
- Belong to the class rather than any specific object.
- Declared using the static keyword.
- Cannot access instance attributes or methods directly.
- Abstract Methods
- Declared in abstract classes or interfaces.
- Do not have a body; must be implemented by subclasses.
How to Declare and Call Methods
Example: Declaring a Method
class Calculator {
// Method to calculate the sum of two numbers
int calculateSum(int a, int b) {
return a + b;
}
}
Example: Calling a Method
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator(); // Create an object
int result = calc.calculateSum(5, 10); // Call the method
System.out.println("Sum: " + result); // Output the result
}
}
Output:
Sum: 15
Static vs Instance Methods
Static Methods | Instance Methods |
---|---|
Declared using the static keyword. | Declared without the static keyword. |
Belong to the class and shared by all objects. | Belong to specific objects. |
Cannot access instance attributes directly. | Can access instance attributes directly. |
Invoked using the class name. | Invoked using an object of the class. |
Example: Static and Instance Methods
class Example {
// Static method
static void staticMethod() {
System.out.println("This is a static method.");
}
// Instance method
void instanceMethod() {
System.out.println("This is an instance method.");
}
}
public class Main {
public static void main(String[] args) {
// Call static method
Example.staticMethod();
// Call instance method
Example ex = new Example();
ex.instanceMethod();
}
}
Output:
This is a static method.
This is an instance method.
Method Parameters
1. Passing Parameters to Methods
You can pass arguments to methods using parameters. These are defined in the method’s declaration.
Example: Method with Parameters
class Greeting {
void sayHello(String name) {
System.out.println("Hello, " + name + "!");
}
}
public class Main {
public static void main(String[] args) {
Greeting greet = new Greeting();
greet.sayHello("Alice");
}
}
Output:
Hello, Alice!
2. Returning Values
A method can return a value using the return keyword.
Example: Method with a Return Value
class MathOperations {
int multiply(int a, int b) {
return a * b;
}
}
public class Main {
public static void main(String[] args) {
MathOperations math = new MathOperations();
int product = math.multiply(4, 5);
System.out.println("Product: " + product);
}
}
Output:
Product: 20
Overloading Methods
Method overloading allows multiple methods in a class with the same name but different parameter lists. It improves code readability and reusability.
Example: Method Overloading
class Calculator {
// Overloaded methods
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Integer Sum: " + calc.add(5, 10));
System.out.println("Double Sum: " + calc.add(5.5, 10.5));
}
}
Output:
Integer Sum: 15
Double Sum: 16.0
Best Practices for Writing Methods
- Follow Naming Conventions: Use descriptive names in camelCase (e.g., calculateArea, findMax).
- Keep Methods Short: Each method should perform a single, specific task.
- Use Access Modifiers: Restrict access to methods appropriately (private, public, etc.).
- Document Methods: Add comments or documentation for clarity.
- Avoid Long Parameter Lists: Keep parameter lists short to improve readability.
Common Mistakes to Avoid
- Not Using Return Statements Correctly: Always match the return type of the method with its declaration.
- Overloading Confusion: Ensure unique parameter lists for overloaded methods.
- Static and Instance Context Mixing: Do not use instance attributes or methods in static methods directly.
Practical Example: Employee Management
class Employee {
String name;
double salary;
// Constructor
Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
// Instance method to display employee details
void displayDetails() {
System.out.println("Employee Name: " + name);
System.out.println("Salary: " + salary);
}
// Static method to calculate yearly bonus
static double calculateBonus(double salary) {
return salary * 0.1; // 10% bonus
}
}
public class Main {
public static void main(String[] args) {
Employee emp = new Employee("John", 50000);
emp.displayDetails();
double bonus = Employee.calculateBonus(emp.salary);
System.out.println("Yearly Bonus: " + bonus);
}
}
Output:
Employee Name: John
Salary: 50000.0
Yearly Bonus: 5000.0