Skip to Content
Think Java
book

Think Java

by Allen B. Downey, Chris Mayfield
May 2016
Beginner content levelBeginner
249 pages
5h 13m
English
O'Reilly Media, Inc.
Content preview from Think Java

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”:

public static void countup(int n) {
    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:

double error = Math.abs(expected - actual);
double height = 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 return statement 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:

public static double calculateArea(double radius) {
    double result = Math.PI * radius * radius;
    return result;
}

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learn Java the Easy Way

Learn Java the Easy Way

Bryson Payne
Optimizing Java

Optimizing Java

Benjamin J. Evans, James Gough, Chris Newland

Publisher Resources

ISBN: 9781491929551Errata Page