Chapter 2 |
Value methods
The value method is a method that returns a value.
The syntax of a value method is similar to the void type methods:
public static returnValueType myMethod( list_of_parameters ) { // statements; return value; }
Unlike void methods, in the return type methods:
- the method header contains the data type of the value (returnValueType) to be returned;
- the last statement of the method body contains a keyword return followed by the value to be returned.
Note: the type of return value must match the value type defined in the method header!
An example of the return type method definition and call:
public class ThreeNumbers { public static double multiplyThreeNumbers(double a, double b, double c) { return a*b*c; } public static void display(double a, double b, double c) { System.out.println("Numbers: " + a + ", " + b + ", " + c); } public static void main(String[] args) { double x = 1.5; double y = 2.25; double z = 3; display(x, y, z); System.out.println("The result of multiplication: " + multiplyThreeNumbers(x, y, z)); System.out.println("The result is " + multiplyThreeNumbers(5, 6.2, 8.0)); } }
Self-assessment
Chapter 2 |