Calling a Non-void Method
In Java, a return statement sends a value from a method back to the place it was called. This value can be used later in your program. A method's return type specifies the type of value the method will return. For example, if a method returns an integer, its return type is int. If it doesn't return anything, its return type is void. That’s why we used the void keyword to make methods before–they didn’t return any value!
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int result = calculator.square(5); // Call a non-void method
// Notice how we can treat the non-void method as a normal expression
System.out.println("The square of 5 is " + result);
}
}Output
The square of 5 is 25
public class Calculator {
// Non-void method with return type 'int'
public int square(int number) {
return number * number; // Returns the result
}
}