Introduce Java Return and give examples
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.
return [expression];
void
), the return
statement must include an expression that matches the return type.void
, you can simply use return;
to exit the method early.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
}
}
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!
}
}
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
}
}
return
statement is essential for methods that need to provide a result back to the caller.void
methods, return;
can be used to exit the method early, but it is optional.