Course Content
Core Java
About Lesson

In Java, methods can return values of specific types after performing some operations or computations.

Return Type

The return type of a method specifies the type of value that the method can return. The return type is declared before the method name in the method signature. Return types can be primitive types (int, double, boolean, etc.), reference types (objects, arrays, etc), or void (indicating no return value).

int calculateSum(int a, int b) {
    return a + b; // Return type is int
}

String getName() {
    return "John Doe"; // Return type is String
}

void printMessage() {
    System.out.println("Hello"); // Return type is void
}

Return Statement

The return statement is used to exit a method and return a value to the caller. The return keyword is followed by an expression (or no expression in the case of void methods).

return expression;

Returning Values

  • Primitive Types: When returning primitive types (int, double, boolean, etc.), the actual value is returned.
  • Reference Types: When returning reference types (objects), a reference to the object is returned.

Void Return Type

Methods with a void return type do not return any value. They are used for performing actions or operations without producing a result. The method ends with a return; statement without any expression. In case of void, return statement is not needed.

Returning Multiple Values

Methods in Java can return only one value. To return multiple values, you can use techniques such as returning arrays, collections, or custom objects encapsulating multiple values.

int[] getMinMax(int[] numbers) {
    // Calculate min and max
    return new int[]{min, max}; // Return array containing min and max
}

class MinMax {
    int min;
    int max;
    // Constructor, getters, and setters
}

MinMax getMinMax(int[] numbers) {
    // Calculate min and max
    return new MinMax(min, max); // Return custom object containing min and max
}

Scroll to Top