2. Methods that Return Values
What is a Return Method?
A method that returns a value provides a result that can be used elsewhere in the program. Unlike void methods, which don't return anything, these methods return a specific data type (e.g., int, double, String).
Why use Return Methods?
Returning values from methods is important when you need the result of a calculation or operation to be used elsewhere in your program.
Syntax:
<code>public class ClassName {
public static returnType methodName() {
// code to be executed
return value;
}
}</code>
Example:
<code>public class MathOperations {
public static int add(int a, int b) {
return a + b;
}
public static double multiply(double x, double y) {
return x * y;
}
}
public class Main {
public static void main(String[] args) {
int sum = MathOperations.add(5, 10);
double product = MathOperations.multiply(4.5, 3.2);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
}
}</code>
Practice Exercise
Create a class Calculator with methods that return the difference, quotient, and remainder of two numbers. Call these methods from the Main class and print the results.