Creating and calling custom class methods

 

Custom class methods

public static return-type method-name(arguments) {
 
statements;
}

where:

return-type is the data type of the value to be returned by the method when it completes its processing. This may be any primitive data type (such as boolean, byte, char, etc..) or the keyword void if the method returns nothing to the caller. If the method returns an object reference, a class name may be specified. This will be covered in a later lesson.

method-name is any valid identifier. It should be meaningful and follow Java coding conventions by beginning with a lower case letter.

arguments is a list of local variables whose values are received as parameters from the caller. If the method requires no arguments, nothing is coded within the parenthesis.

statements are one or more statements that define the method's processing. In addition to the local variables received as parameters, other local variables may be declared.

return expression;

is required where expression is compatible with the return-type specified in the method header. If the method header indicates that no value is to be returned (void is specified), a null return statement such as

return;

may be coded. Otherwise, processing will automatically end when the closing brace of the method is reached.

public static double extendedPrice(int quantity, double unitPrice)

it expects to receive two parameters. If a calling method has an int variable named qty and a double variable named price, it can call the extendedPrice method with the following expression:

extendedPrice(qty, price)

The caller's values of qty and price will automatically be copied and assigned to the method's local variables named quantity and unitPrice.

When parameters are passed:

  1. The match-up is entirely positional. The first parameter value is copied and assigned to the first local variable declared in the method header, the second parameter value is copied and assigned to the second local variable declared in the method header, etc..

  2. Trying to pass too few or too many parameters will result in a compile error.

  3. Variable names are irrelevant. Even if the same identifier is used in both the calling method and in the class method, they reference different memory areas.

  4. Data types must be compatible and, if necessary, widening conversions are automatically performed. For example, the extendedPrice method could be called with a byte and an int because they can be widened to the expected int and double.

 

Sample program

The following sample program performs temperature conversions using a class method named convertTemp which is called from the application's main() method:

public class App {
  public static void main(String[] args) {

    // Variables.

    double oldTemp;
    char scale;
    double newTemp;
    char again;

    // Loop to process one temperature conversion.

    do {

      // Get data from the user.

      Utility.separator(50, '>');
      System.out.print("Enter temperature: ");
      oldTemp = Keyboard.readDouble();
      System.out.print("Current scale? (C/F): ");
      scale = Keyboard.readChar();

      // Process the conversion request.

      Utility.skip();
      switch (scale) {

        // Cases for a valid scale.

        case 'C':
        case 'c':
        case 'F':
        case 'f':
          newTemp = convertTemp(oldTemp, scale);
          System.out.println("\tConverted temperature: " +
            Utility.fixedFormat(newTemp, 2));
          break;

        // Default case for an invalid scale.

        default:
          System.out.println("\tInvalid scale");
          break;
      }

      // Ask if they want to do another and repeat as requested.

      Utility.skip();
      System.out.print("Again? (Y/N): ");
      again = Keyboard.readChar();
    } while (again == 'Y' || again == 'y');
  }

  // Class method to convert a temperature from either centigrade to
  // fahrenheit or fahrenheit to centigrade.

  public static double convertTemp(double temperature, char scale) {

    // If the scale is centigrade, convert the temperature to
    // fahrenheit. Otherwise, convert it to centigrade.

    if (scale == 'C' || scale == 'c') {
      return ((9 * temperature) / 5) + 32;
    }
    else {
      return (5 * (temperature -32)) / 9;
    }
  }
}

Notes:

  1. The convertTemp() method expects to receive two parameters. The first must be a double (or able to be widened to a double) that represents the temperature to be converted. The second must be a char that represents the scale of the temperature to be converted.

  2. Because the convertTemp() method is defined within the same class as the main() method, it can be called without specifying its class name. Alternatively, App.convertTemp() could have been called.

  3. The convertTemp() method returns a double so it can be called anywhere a double makes sense. That is why it can be assigned to the double variable newTemp.

  4. Because convertTemp() is public, it may be called from any other class. That means no one else in the history of mankind will ever have to write another temperature conversion method as long as they can call App.convertTemp().

 

Lab exercise for Ferris students

E-mail your answers to this assignment no later than the due date listed in the class schedule.

 

Review questions

  1. Which one statement is true about the application shown below? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
8
9
10
public class App {
  public static void main(String[] args) {
    int length = 5;
    int width = 3;
    System.out.println("Area is " + area(length, width));
  }
  public static double area(double len, double wid) {
    return len * wid;
  }
}
  1. a compile error will occur at line 5

  2. a compile error will occur at line 7

  3. a compile error will occur at line 8

  4. the program will compile but an error will occur at run time

  5. the program will compile and run to display "Area is 15.0"

  1. Which one statement is true about the application shown below? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
8
9
10
public class App {
  public static void main(String[] args) {
    int hours = 5;
    double rate = 7.25;
    System.out.println("Gross pay: " + grossPay());
  }
  public static double grossPay() {
    return hours * rate;
  }
}
  1. a compile error will occur at line 5

  2. a compile error will occur at line 7

  3. a compile error will occur at line 8

  4. the program will compile but an error will occur at run time

  5. the program will compile and run to display "Gross pay: 36.25"

  1. Which one statement is true about the application shown below? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
8
9
10
public class App {
  public static void main(String[] args) {
    int hours = 5;
    double rate = 7.25;
    System.out.println("Gross pay: " + grossPay(rate, hours));
  }
  public static double grossPay(int hours, double rate) {
    return hours * rate;
  }
}
  1. a compile error will occur at line 5

  2. a compile error will occur at line 7

  3. a compile error will occur at line 8

  4. the program will compile but an error will occur at run time

  5. the program will compile and run to display "Gross pay: 36.25"

  1. Which one statement is true about the application shown below? The line numbers are for reference purposes only.

1
2
3
4
5
6
7
8
9
10
public class App {
  public static void main(String[] args) {
    int hours = 5;
    double rate = 7.25;
    System.out.println("Gross pay: " + grossPay(hours, rate));
  }
  public static double grossPay(int hours, double rate) {
    double gross = hours * rate;
  }
}
  1. a compile error will occur at line 5

  2. a compile error will occur at line 8

  3. a compile error will occur at line 9

  4. the program will compile but an error will occur at run time

  5. the program will compile and run to display "Gross pay: 36.25"