Java Reference
In-Depth Information
Return
To send a value out as the result of a method that can be used in an expression
in your program. Void methods do not return any value.
If you had such a method, you could ask for the square root of 2.5 by writing code
like this:
// assuming you had a method named sqrt
double answer = sqrt(2.5);
The sqrt method has a parameter (the number whose square root you want to
find), and it also returns a value (the square root). The actual parameter 2.5 goes
“into” the method, and the square root comes out. In the preceding code, the returned
result is stored in a variable called answer .
You can tell whether or not a method returns a value by looking at its header. All
the methods you've written so far have begun with public static void. The
word void is known as the return type of the method.
The void return type is a little odd because, as its name implies, the method
returns nothing. A method can return any legal type: an int ,a double , or any other
type. In the case of the sqrt method, you want it to return a double , so you would
write its header as follows:
public static double sqrt(double n)
As in the previous case, the word that comes after public static is the return
type of the method:
public static double sqrt(double n)
return type
Fortunately, you don't actually need to write a method for computing the square root
of a number, because Java has one that is built in. The method is included in a class
known as Math that includes many useful computing methods. So, before we discuss
the details of writing methods that return values, let's explore the Math class and what it
has to offer.
The Math Class
In Chapter 1 we mentioned that a great deal of predefined code, collectively known
as the Java class libraries, has been written for Java. One of the most useful classes is
Math . It includes predefined mathematical constants and a large number of common
mathematical functions. The Math class should be available on any machine on
which Java is properly installed.
 
Search WWH ::




Custom Search