Methods in Java

A method is a block of code created within a class to perform a specific task. It consists of instructions that can be called or invoked to execute an action. Methods are also referred to as functions. By using methods, programmers can create modular, readable, and maintainable code structures, thereby improving code manageability and reusability.

Method Signature

The signature of a method in Java consists of the method name and the parameter list. It helps to uniquely identify and differentiate one method from another. The return type is not part of the method signature.

The general syntax of a method signature in Java is as follows:

accessModifier returnType methodName(parameterList) {

}

Here's a break down and explanation of each part of the method signature:

  • accessModifier: The access modifier are used to control the visibility and accessibility of methods from other parts of the program.
  • returnType: The return type specifies the type of value that the method will return after performing its task. It can be any valid data type in Java, or it can be void if the method does not return any value.
  • methodName: The method name is a unique identifier for the method. It should be chosen descriptively to indicate the purpose or action performed by the method.
  • parameterList: The parameter list is a comma-separated list of parameters enclosed within parentheses. Each parameter consists of the parameter type followed by the parameter name. Parameters are optional and can be used to pass data into the method for processing.

Creating Methods in Java

Follow these steps to create a method in Java:

  1. Define Method Accessibility: Use access modifiers like public, private, or protected.
  2. Specify Return Type: Declare the data type or use void.
  3. Provide Method Name: Assign a descriptive name.
  4. Define Parameters: Enclose parameters within parentheses.
  5. Implement Method Body: Define the code block.

Example:

public int multiply(int x, int y) {
    int result = x * y;
    return result;
}

In the example provided above, the public keyword allows the method to be accessible from any other class, regardless of the location of the accessing code. The method is named multiply and has a return type of int, indicating that it will return a value of type int. It accepts two parameters of type int, named x and y.

Within the method, the two input numbers (x and y) are multiplied, and the result is stored in a variable named result. Subsequently, the result variable is returned using the return keyword.

Invoking Methods in Java

Follow these steps to invoke or call a method in Java:

  1. Identity the name of the method you want to call. Make sure you know the method's name and the parameters it expects (if any).
  2. Identify the object or class on which the method is defined. Methods are associated with either an object (instance methods) or a class (static methods). You need to determine whether the method is an instance method or a static method.
  3. To invoke an instance method, create an object (instance) of the class if the method is an instance method. Use the object name, followed by a dot (.) operator, to call the method. Provide the necessary arguments (if any) within parentheses.

    MyClass obj = new MyClass(); // Create an object of MyClass
    obj.myMethod(); // Call the instance method myMethod()

    To invoke static method, call it directly on the class itself, without creating an instance. Use the class name, followed by a dot (.) operator, to call the static method. Provide the necessary arguments (if any) within parentheses.

    MyClass.myStaticMethod(); // Call the static method myStaticMethod()

    Make sure that the method you are invoking is visible and accessible from the current scope (based on its access modifier). Also, ensure that the method name, parameters, and return type match the method's declaration.

Types of Methods

In Java, methods can be categorized into several types based on their characteristics and functionality. Here are some common types of methods in Java:

  1. Instance Methods:
  2. Instance methods are associated with objects of a class. They operate on the specific instance variables and can access other instance methods and variables of the same class. Instance methods are invoked on an instance of the class using the dot notation.

    Example:

    //Calculator.java 
    public class Calculator {
    
      public int multiply(int x, int y) {
        int result = x * y;
        return result;
      }
    
    }

    To call an instance method:

    //Test.java 
    public class Test {
    
      public static void main(String[] args) {
        Calculator calc = new Calculator();
        int result = calc.multiply(2, 5);
        System.out.println("Result = " + result);
      }
    
    }

    Output:

    Result = 10
  3. Static Methods:
  4. Static methods belong to the class itself rather than individual instances. They can be called directly on the class itself without creating an instance. Static methods cannot access instance variables or methods directly, but they can access other static methods and static variables.

    Example:

    //Calculator.java 
    public class Calculator {
    
      public static int multiply(int x, int y) {
        int result = x * y;
        return result;
      }
    
    }

    To call a static method:

    //Test.java 
    public class Test {
    
      public static void main(String[] args) {
        int result = Calculator.multiply(2, 5);
        System.out.println("Result = " + result);
      }
    
    }

    Output:

    Result = 10
  5. Return Type Methods:
  6. Return type methods are those methods that return a value after their execution. This returned value can be of any primitive data type, an object of a class, or an array.

    Example:

    //Calculator.java 
    public class Calculator {
    
      public double add(double x, double y) {
        double result = x * y;
        return result;
      }
    
    }
  7. Void Methods:
  8. Void type methods are those methods that do not return any value upon their execution.

    Example:

    public class Student {
      private String firstName;
      private String lastName;
      private double balance;
    
      public void populateUserProfile() {
        this.firstName = "Danny";
        this.lastName = "A";
        this.balance = 7000000.00;
      }
    
      public static void main(String[] args) {
        Student student = new Student();
        student.populateUserProfile();
        System.out.println("First Name : " + student.firstName);
        System.out.println("Last Name : " + student.lastName);
        System.out.println("Bank Balance : $" + student.balance);
      }
    
    }
  9. Parameterized Methods:
  10. Parameterized methods are those methods that accept parameters, allowing the caller to provide specific values needed for the method's execution.

    Example:

    public class Student {
      private String firstName;
      private String lastName;
      private double balance;
    
      public void populateUserProfile(String firstName, String lastName, double balance) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.balance = balance;
      }
    
      public static void main(String[] args) {
        Student student = new Student();
        student.populateUserProfile("Danny", "L", 1000020.00);
        System.out.println("First Name : " + student.firstName);
        System.out.println("Last Name : " + student.lastName);
        System.out.println("Bank Balance : $" + student.balance);
      }
    
    }
  11. Varargs Methods:
  12. Varargs methods allow a variable number of arguments to be passed to the method. They are declared using an ellipsis (...) in the method parameter, and the arguments are treated as an array within the method. A varargs parameter (variable-length arguments) must be the last parameter in a method's parameter list. This is because a varargs parameter can accept a variable number of arguments, and the compiler needs to be able to distinguish it from other parameters.

    Example:

    public class Student {
      private String firstName;
      private String lastName;
      private double balance;
    
      public void populateUserProfile(double balance, String... names) {
        this.firstName = names[0];
        this.lastName = names[1];
        this.balance = balance;
      }
    
      public static void main(String[] args) {
        Student student = new Student();
        student.populateUserProfile(1000020.00, "Danny", "L");
        System.out.println("First Name : " + student.firstName);
        System.out.println("Last Name : " + student.lastName);
        System.out.println("Bank Balance : $" + student.balance);
      }
    
    }
  13. Getter and Setter Methods:
  14. Getter methods, also known as accessor methods, are used to retrieve the values of private instance variables. Setter methods, also known as mutator methods, are used to modify or set the values of private instance variables. They provide controlled access to the private fields of a class.

    Example:

    public class Student {
      private String firstName;
      private String lastName;
      private double balance;
    
      public String getFirstName() {
        return firstName;
      }
    
      public void setFirstName(String firstName) {
        this.firstName = firstName;
      }
    
      public String getLastName() {
        return lastName;
      }
    
      public void setLastName(String lastName) {
        this.lastName = lastName;
      }
    
      public double getBalance() {
        return balance;
      }
    
      public void setBalance(double balance) {
        this.balance = balance;
      }
    
      public static void main(String[] args) {
        Student student = new Student();
        student.setFirstName("Danny");
        student.setLastName("L");
        student.setBalance(2000000.00);
        
        System.out.println("First Name = " + student.getFirstName());
        System.out.println("Last Name = " + student.getLastName());
        System.out.println("Balance = " + student.getBalance());
      }
    
    }
  15. Overloaded Methods:
  16. Overloaded methods are methods with the same name but different parameter lists within the same class. They allow multiple methods with the same name to perform different operations based on the type, number, or order of parameters.

    Example:

    public class Calculator {
        
        // Overloaded method to add two integers
        public int add(int a, int b) {
            return a + b;
        }
    
        // Overloaded method to add three integers
        public int add(int a, int b, int c) {
            return a + b + c;
        }
    
        // Overloaded method to add two doubles
        public double add(double a, double b) {
            return a + b;
        }
    
        public static void main(String[] args) {
            // Create an object of the Calculator class
            Calculator calc = new Calculator();
    
            // Call the overloaded methods
            System.out.println("Sum of 5 and 10: " + calc.add(5, 10));
            System.out.println("Sum of 5, 10, and 15: " + calc.add(5, 10, 15));
            System.out.println("Sum of 5.5 and 10.5: " + calc.add(5.5, 10.5));
        }
    }
  17. Recursive Methods:
  18. Recursive methods are methods that call themselves, either directly or indirectly, to solve a problem by breaking it down into smaller subproblems. They typically have a base case that terminates the recursion and one or more recursive calls that solve the smaller subproblems.

    Example:

    public class FactorialCalculator {
    
        // Recursive instance method to calculate the factorial of a non-negative integer
        public int calculateFactorial(int n) {
            // Base case: factorial of 0 is 1
            if (n == 0) {
                return 1;
            }
            // Recursive case: factorial of n is n multiplied by factorial of (n - 1)
            else {
                return n * calculateFactorial(n - 1);
            }
        }
    
        public static void main(String[] args) {
            // Create an object of the FactorialCalculator class
            FactorialCalculator calculator = new FactorialCalculator();
    
            // Calculate and display the factorial of 5 using the non-static method
            int number = 5;
            System.out.println("Factorial of " + number + " is: " + calculator.calculateFactorial(number));
        }
    }
  19. Abstract Methods:
  20. Abstract methods are declared in abstract classes or interfaces but do not have a method body. They provide a contract for the subclasses or implementing classes to define their own implementation of the method.

    Example:

    // Abstract Shape class
    abstract class Shape {
        // Abstract method to get the area
        public abstract double getArea();
    
        // Abstract method to get the perimeter (circumference)
        public abstract double getPerimeter();
    }
    
    // Concrete Circle subclass
    class Circle extends Shape {
        private double radius;
    
        public Circle(double radius) {
            this.radius = radius;
        }
    
        @Override
        public double getArea() {
            return Math.PI * radius * radius;
        }
    
        @Override
        public double getPerimeter() {
            return 2 * Math.PI * radius;
        }
    }
    
    // Concrete Rectangle subclass
    class Rectangle extends Shape {
        private double width;
        private double height;
    
        public Rectangle(double width, double height) {
            this.width = width;
            this.height = height;
        }
    
        @Override
        public double getArea() {
            return width * height;
        }
    
        @Override
        public double getPerimeter() {
            return 2 * (width + height);
        }
    }
    
    // Main class to test the Shape subclasses
    public class ShapeTest {
        public static void main(String[] args) {
            // Create instances of Circle and Rectangle
            Shape circle = new Circle(5);
            Shape rectangle = new Rectangle(4, 6);
    
            // Display area and perimeter of the Circle
            System.out.println("Circle Area: " + circle.getArea());
            System.out.println("Circle Perimeter: " + circle.getPerimeter());
    
            // Display area and perimeter of the Rectangle
            System.out.println("Rectangle Area: " + rectangle.getArea());
            System.out.println("Rectangle Perimeter: " + rectangle.getPerimeter());
        }
    }
  21. Final Methods:
  22. Final methods cannot be overridden by subclasses. They are declared with the final modifier to prevent any modification in the method implementation.

    Example:

    // BankAccount class representing a generic bank account
    class BankAccount {
        protected double balance;
    
        public BankAccount(double initialBalance) {
            this.balance = initialBalance;
        }
    
        // Final method to calculate interest on the bank account
        public final double calculateInterest() {
            // Assume a simple interest rate of 5% for demonstration purposes
            double interestRate = 0.05;
            return balance * interestRate;
        }
    
        // Other methods and functionalities related to a bank account
        // ...
    }
    
    // SavingsAccount class representing a savings account, extending BankAccount
    class SavingsAccount extends BankAccount {
        public SavingsAccount(double initialBalance) {
            super(initialBalance);
        }
    
        // Attempt to override the final method (this will result in a compile-time error)
        /*
        @Override
        public double calculateInterest() {
            // Implementation for calculating interest on a savings account
            // ...
        }
        */
    }
    
    // Main class to test the final method in the BankAccount class
    public class BankSystem {
        public static void main(String[] args) {
            // Create a SavingsAccount instance with an initial balance of $1000
            SavingsAccount savingsAccount = new SavingsAccount(1000);
    
            // Calculate and display the interest on the savings account
            System.out.println("Interest on Savings Account: $" + savingsAccount.calculateInterest());
        }
    }