Parameters and Return Types in Java Methods

In Java, methods can have parameters (inputs) and return types (outputs). Let's explore how to use parameters and return types in-depth.

Parameters in Method Declaration:

Parameters are specified in the method declaration within parentheses. They act as placeholders for values that will be passed when the method is invoked.


returnType methodName(parameterType1 parameterName1, parameterType2 parameterName2, ...) {
  // Method body
  // Code to perform the task using parameters
  return returnValue; // If the method has a return type
}

Example with Parameters:

Let's look at an example of a method that calculates the area of a rectangle using length and width as parameters:


public class Rectangle {
  public double calculateArea(double length, double width) {
    return length * width;
  }
}

public class Main {
  public static void main(String[] args) {
    Rectangle rectangle = new Rectangle();
    double area = rectangle.calculateArea(5.0, 3.0);
    // Result: 15.0
  }
}

Return Types in Method Declaration:

The return type specifies the type of value that the method will return. If a method doesn't return a value, use void as the return type.


returnType methodName(parameterType parameterName, ...) {
  // Method body
  // Code to perform the task
  return returnValue; // If the method has a return type
}

Example with Return Type:

Let's look at an example of a method that calculates the sum of two numbers and returns the result:


public int calculateSum(int num1, int num2) {
  return num1 + num2;
}

Note:

Parameters and return types provide flexibility and reusability in Java methods. Ensure that the data types match and consider the design of your methods based on the task they need to perform.