Understanding Java Return Statement with Examples

Respondido usando: GPT-4o-mini porJava Q&A Hub

Pergunta:

Introduce Java Return and give examples

Resposta:

In Java, the return statement is used to exit from a method and optionally return a value to the caller. The type of value returned must match the method's return type specified in its declaration. If a method is declared with a return type of void, it cannot return a value.

Syntax

return [expression];
  • If the method has a return type (other than void), the return statement must include an expression that matches the return type.
  • If the method is void, you can simply use return; to exit the method early.

Examples

Example 1: Method with a return type

Here’s a simple example of a method that returns an integer value:

public class ReturnExample {
    // Method that returns the sum of two integers
    public int add(int a, int b) {
        return a + b; // Returning the sum
    }

    public static void main(String[] args) {
        ReturnExample example = new ReturnExample();
        int result = example.add(5, 10); // Calling the method
        System.out.println("The sum is: " + result); // Output: The sum is: 15
    }
}

Example 2: Method with void return type

In this example, we have a method that does not return any value:

public class VoidReturnExample {
    // Method that prints a message
    public void printMessage(String message) {
        System.out.println(message);
        return; // Optional, can be omitted
    }

    public static void main(String[] args) {
        VoidReturnExample example = new VoidReturnExample();
        example.printMessage("Hello, World!"); // Output: Hello, World!
    }
}

Example 3: Early return

You can use the return statement to exit a method early based on a condition:

public class EarlyReturnExample {
    // Method that checks if a number is positive
    public boolean isPositive(int number) {
        if (number <= 0) {
            return false; // Early return if the number is not positive
        }
        return true; // Return true if the number is positive
    }

    public static void main(String[] args) {
        EarlyReturnExample example = new EarlyReturnExample();
        System.out.println(example.isPositive(5));  // Output: true
        System.out.println(example.isPositive(-3)); // Output: false
    }
}

Summary

  • The return statement is essential for methods that need to provide a result back to the caller.
  • For void methods, return; can be used to exit the method early, but it is optional.
  • The return type of the method must match the type of the value returned.