Content received from: http://JavaFAQ.nu/java-article428.html


The Java Lesson 14: Creating and calling custom class methods
Saturday, March 20, 2004 (00:00:00)

Posted by jalex

All Java Lessons contents page | Java Lesson 1 | Java Lesson 2 | Java Lesson 3 | Java Lesson 4 | Java Lesson 5 | Java Lesson 6 | Java Lesson 7 | Java Lesson 8 | Java Lesson 9 | Java Lesson 10 | Java Lesson 11 | Java Lesson 12 | Java Lesson 13 | Java Lesson 14 | Java Lesson 15 | Java Lesson 16 | Java Lesson 17 | Java Lesson 18 | Java Lesson 19 | Java Lesson 20 | Java Lesson 21 | Java Lesson 22 | Java Lesson 23 | Java Lesson 24 | Java Lesson 25 | Java Lesson 26 | Java Lesson 27 | Java Lesson 28 | Java Lesson 29 | Java Lesson 30 | Java Lesson 31 | Java Lesson 32 | Java Lesson 33 | Java Lesson 34 | Java Lesson 35 | Java Lesson 36 | Java Lesson 37 | Java Lesson 38 | Java Lesson 39 | Java Lesson 40 | Java Lesson 41 | Java Lesson 42 | Java Lesson 43 | Java Lesson 44 | Java Lesson 45 | Java Lesson 46

The Java Lesson 14

Creating and calling custom class methods

Custom class methods

  • Can be defined within any class but not within another method. Methods can not be nested.

  • Are associated with the class itself and not with an object of the class. This is indicated by the use of the static keyword within the method's header. No object must exist to call a class method.

  • Have the general syntax

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.

  • May have one or more return statements. If the method header indicates that the method is to return a value, a return statement of the form

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.

  • Receive a copy of values passed from the caller. For security reasons, a class method is never allowed to access the primitive variables of the calling method (objects are a bit different and will be covered later). For example, if a class method is defined with the following header:

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.

  • Have variables with a limited scope. The memory space of method local variables is automatically garbage collected when the method ends. Only the value returned from the method (if any) is available to the caller.



Creating and calling custom class methods

Custom class methods

  • Can be defined within any class but not within another method. Methods can not be nested.

  • Are associated with the class itself and not with an object of the class. This is indicated by the use of the static keyword within the method's header. No object must exist to call a class method.

  • Have the general syntax

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.

  • May have one or more return statements. If the method header indicates that the method is to return a value, a return statement of the form

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.

  • Receive a copy of values passed from the caller. For security reasons, a class method is never allowed to access the primitive variables of the calling method (objects are a bit different and will be covered later). For example, if a class method is defined with the following header:

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.

  • Have variables with a limited scope. The memory space of method local variables is automatically garbage collected when the method ends. Only the value returned from the method (if any) is available to the caller.

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(" Converted temperature: " +
Utility.fixedFormat(newTemp, 2));
break;

// Default case for an invalid scale.

default:
System.out.println(" Invalid 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"