Chapter 6. Value Methods
Some of the methods we have used, like the Math methods, return values. But all the methods we have written so far have been void; that is, they don’t return values. In this chapter, we’ll write methods that return values, which we call value methods.
Return Values
When you invoke a void method, the invocation is usually on a line all by itself. For example, here is the countup method from “Recursive Methods”:
publicstaticvoidcountup(intn){if(n==0){System.out.println("Blastoff!");}else{countup(n-1);System.out.println(n);}}
And here is how it is invoked:
countup(3);System.out.println("Have a nice day.");
On the other hand, when you invoke a value method, you have to do something with the return value. We usually assign it to a variable or use it as part of an expression, like this:
doubleerror=Math.abs(expected-actual);doubleheight=radius*Math.sin(angle);
Compared to void methods, value methods differ in two ways:
They declare the type of the return value (the return type);
They use at least one
returnstatement to provide a return value.
Here’s an example: calculateArea takes a double as a parameter and returns the area of a circle with that radius:
publicstaticdoublecalculateArea(doubleradius){doubleresult=Math.PI*radius*radius;returnresult;}
As usual, this method is public and static. But in the place where we are used to seeing void, we see double, which means that the return value from this method is a double ...