Week 4, Notes 2 – Methods

Return values

Useful methods often return a result to the user.  Consider a clock as a method: you ask it what time it is, and it returns you the time.

Parameters

Likewise, it is useful to be able to give a method a set of information to use to help do its job.  Consider a blender: you put in yogurt, orange juice, frozen banana, a little vanilla, some cinnamon, strawberry or blueberry if you have them; call the blender to work; and the blender returns a smoothie.

Method Signature syntax

public static <return_type> <method_name> (

<param1_type> <param1_name> ,  <param2_type> <param2_name> )

 

The brace that opens the body of the method follows the signature.  Do not put a ; following the signature. 

A parameter declaration is like a variable declaration.  It must have a type – so far the only type we have used is double – and a name, which you, as the programmer, make up.

 

There may be any number of parameter declarations, including 0, each separated by a comma.

 

Parameter declarations that appear in the signature of a method declaration are known as formal parameters.

 

For example:

   public static double getCelciusFor( double fahrTemp)

·         takes (or receives) one value of type double (this double is referred to as fahrTemp inside the body of the method)

·         returns a value of type double

·         Notice the body of the method is not shown here

 

Method calls

To call a method that you have written, type the name of the method followed by (, followed by one value for each parameter declared in the method signature, e.g.,

// return the Celsius equivalent of the Fahrenheit temperature 32.0 degrees.

getCelsiusFor( 32.0);

 

You probably will want to assign the value returned by the method to a variable, so you can use it later on, e.g.,

 

double tempInC;

tempInC = getCelsiusFor(32.0);

 

Examples

Write a program that:

  1. reads a Fahrenheit temperature from the user
  2. calls the getCelsiusFor() method, which converts it to Celsius
  3. if the result is above freezing, print “above freezing”
  4. otherwise print “colder than ol’ billy”
  5. reads two doubles, num and toRaiseTo, from the user
  6. calls the raiseToPower() method, which raises num to the toRaiseTo power
  7. print the value the raiseToPower() method returns

 

see ../demos/W04N02.java