Return Statement In Java

return Statement In Java

In Java, the return statement is used to exit a method and optionally return a value to the caller. Here are some examples of how the return statement works in Java:

Returning a Value from a Method

You can use the return statement to return a value from a method. The return type of the method should match the type of value you’re returning. Here’s an example:

				
					public int add(int a, int b) {
    int sum = a + b;
    return sum; // Returns the sum of a and b
}

				
			

In this example, the add method takes two integers as input, calculates their sum, and returns the result as an int.

Returning Early from a Method

You can use the return statement to exit a method early, before reaching the end of the method. For example, you might have a method that checks a condition and returns immediately if the condition is met:

				
					public boolean isPositive(int number) {
    if (number > 0) {
        return true; // Return early if the number is positive
    } else {
        return false;
    }
}

				
			

In this example, the isPositive method returns true if the input number is positive, and it returns false for non-positive numbers.

Returning from Void Methods

Void methods (methods with a return type of void) don’t return a value, but you can use return to exit the method early. In this case, you don’t provide a value after return, as there’s nothing to return. Here’s an example:

				
					public void printMessage(String message) {
    if (message == null) {
        System.out.println("Message is null.");
        return; // Exit the method early
    }
    System.out.println(message);
}

				
			

In this example, if the message is null, the method prints a message and then exits early using return.

Returning from a Loop

You can use return to exit a loop (e.g., for or while) early if a certain condition is met. Here’s an example:

				
					public int findFirstPositive(int[] numbers) {
    for (int num : numbers) {
        if (num > 0) {
            return num; // Exit the method and return the first positive number found
        }
    }
    return -1; // Return -1 if no positive numbers are found
}

				
			

In this example, the method searches for the first positive number in an array and returns it. If no positive number is found, it returns -1.

The return statement is a fundamental feature in Java for controlling the flow of your program and providing results from methods to the calling code.