Method Declaration

Syntax and components of methods

Interview Relevant: Understanding method structure is fundamental
7 min read

Methods in Java

A method is a block of code that performs a specific task. Methods promote code reusability, modularity, and organization.

Method Structure

accessModifier returnType methodName(parameters) {
    // method body
    return value;  // if returnType is not void
}

Components Explained

  • Access Modifier: public, private, protected, or default
  • Return Type: Data type of returned value, or void
  • Method Name: Identifier following camelCase convention
  • Parameters: Input values (optional)
  • Method Body: The code to execute

💡 Naming Convention: Method names should be verbs in camelCase: calculateTotal(), getUserById(), isValid()

Code Examples

Different method declaration patterns

java
1// Basic method declaration
2public class Calculator {
3    
4    // No parameters, no return value
5    public void greet() {
6        System.out.println("Hello!");
7    }
8    
9    // With parameters, with return value
10    public int add(int a, int b) {
11        return a + b;
12    }
13    
14    // Private method (internal use only)
15    private void logOperation(String op) {
16        System.out.println("Performed: " + op);
17    }
18    
19    // Method with multiple parameters
20    public double calculateArea(double length, double width) {
21        return length * width;
22    }
23}

Different ways to call methods

java
1// Calling methods
2Calculator calc = new Calculator();
3
4// Call void method
5calc.greet();  // Output: Hello!
6
7// Call method with return value
8int sum = calc.add(5, 3);
9System.out.println(sum);  // 8
10
11// Use return value directly
12System.out.println(calc.add(10, 20));  // 30
13
14// Chain method calls
15String result = "hello".toUpperCase().substring(0, 3);
16System.out.println(result);  // "HEL"
17
18// Store in variable vs use directly
19double area = calc.calculateArea(5.0, 3.0);
20// OR
21if (calc.calculateArea(5.0, 3.0) > 10) {
22    System.out.println("Large area!");
23}

Method modifiers: static, final, synchronized

java
1// Method modifiers
2public class Example {
3    
4    // Static method - called on class, not instance
5    public static int multiply(int a, int b) {
6        return a * b;
7    }
8    
9    // Final method - cannot be overridden
10    public final void criticalMethod() {
11        System.out.println("Cannot override this!");
12    }
13    
14    // Synchronized method - thread-safe
15    public synchronized void threadSafeMethod() {
16        // Only one thread can execute at a time
17    }
18    
19    // Abstract method (in abstract class)
20    // public abstract void mustImplement();
21}
22
23// Calling static method
24int product = Example.multiply(4, 5);  // No instance needed!

Method naming conventions and patterns

java
1// Method naming best practices
2public class UserService {
3    
4    // Verb phrases for actions
5    public void createUser(String name) { }
6    public void deleteUser(int id) { }
7    public void updateProfile(User user) { }
8    
9    // get/set for accessors
10    public String getName() { return ""; }
11    public void setName(String name) { }
12    
13    // is/has/can for boolean returns
14    public boolean isActive() { return true; }
15    public boolean hasPermission(String perm) { return false; }
16    public boolean canEdit() { return true; }
17    
18    // find/search/query for lookups
19    public User findById(int id) { return null; }
20    public List<User> searchByName(String name) { return null; }
21    
22    // calculate/compute for computations
23    public double calculateTotal() { return 0.0; }
24    public int computeChecksum() { return 0; }
25}

Use Cases

  • Encapsulating reusable logic
  • Breaking down complex tasks
  • Implementing business logic
  • Creating utility functions
  • Building APIs
  • Data processing operations

Common Mistakes to Avoid

  • Not following naming conventions
  • Methods doing too many things (violates SRP)
  • Excessive parameters (consider object parameter)
  • Ignoring return values
  • Calling instance method without object
  • Not declaring proper access modifier