Next: None. Up: Logic and class members. Previous: Logical operators.


Defining methods

It's easy to define your own methods. In fact, we've been doing it all along.

import csbsju.cs160.*;

public class Fahr {
    public static double toCelsius(double fahr) {
        return (fahr - 32.0) * 5.0 / 9.0;
    }

    public static void run(double input) {
        IO.print(input);
        IO.print(" degrees Celsius is ");
        IO.print(Fahr.toCelsius(input));
        IO.println(" degrees Fahrenheit.");
    }
}
In this example, we've defined two methods: Fahr.run and Fahr.toDouble. The toCelsius method takes a double for an argument and returns a double. (We know it returns a double because we wrote public static double. When we write public static void, we're saying that the method doesn't return anything.)

Let's say we call Fahr.run(98.6). The computer will handle the first two lines of Fahr.run - it will print ``98.6 degrees Celsius is ,'' Then it gets to the third line. At this point, it gets to where it calls Fahr.toCelsius, handing it 98.6 for its first argument (98.6 being the value of the expression input).

The Fahr.toCelsius method accepts 98.6 into its fahr variable. In this case, it has just one statement to do: a return statement, which exits the method. If the method is to return something (that is, the return type isn't void), it returns the value of the expression following it. To compute this value, it computes (98.6-32.0)*5.0/9.0, which is 37.0. This is the return value for this call to Fahr.toCelsius.

The computer now picks up from where it left off in Fahr.run(). It just computed that 37.0 is the return value for Fahr.toCelsius(98.6), and this 37.0 is passed along to the IO.print() method. The computer displays 37.0 in the window. Then it executes the fourth line of Fahr.run(), completing the line:

98.6 degrees Celsius is 37.0 degrees Fahrenheit.

Incidentally, Java assumes we mean the name of our own class when we omit it. We could have written the third line of Fahr.run() as

        IO.print(toCelsius(input));
The class for toCelsius() isn't specified, but Java would assume we meant Fahr (since that's the class that Fahr.run() is in). So it would work just the same.

Exercise


Next: None. Up: Logic and class members. Previous: Defining methods.