Methods and Parameters
Objective #1: Call methods.
- Methods are reusable sections of code that perform actions.
- Many methods come from classes that are built into the Java language.
For example, the println method is found in the System class that is automatically available in any Java program. It allows you to display a string with the statement
System.out.println("hello world");
The pow method comes from the Math class and can be used in any Java program as in:
System.out.println(Math.pow(3, 2)); // 9 is displayed since 3 squared equals 9
- There are some classes that exist in Java for the sole purpose of containing handy, reusable methods. Such classes are called utility classes. Math, Integer, and Double are examples of utility classes since they contain so many useful methods including Math.pow(), Math.sqrt(), Math.abs(), Integer.parseInt(), Double.parseDouble() and even constants like Math.PI, Integer.MIN_VALUE, and Integer.MAX_VALUE.
- You should research methods like the those explained above in the Java API to learn how they work and to find other useful ones.
Objective #2: Identify the parts of a method.
- Very often, as a programmer, it is wise to create your own method.
- Here is an example of a method that you might create for use in a program:
public double computeAreaTriangle(int base, int height)
{
return base * height / 2.0;
}
- The name that the programmer chose for the method above is computeAreaTriangle. The name of a method should begin with a lowercase letter. The name of a method should be descriptive as to its purpose. Very often, a verb is used in the name of the method to help describe what the method does since the purpose of a method is usually to perform an action.
- The first line of a method is called the method header as in
public double computeAreaTriangle(int base, int height)
- The body of the method is the part of the method that is included in its required curly braces as in
{
return base * height / 2.0;
}
- The method name, parameters, and body statements together are
called the method's definition.
Here is the complete definition of the method above. Technically the public double part of the header is not considered to be in the method's definition.
computeAreaTriangle(int base, int height)
{
return base * height / 2.0;
}
- The parameter list for a method is the list of parameters that may be found in the set of parentheses in the method header. The parameter list for the computeAreaTriangle method above is int base, int height
Note that it is not accurate to call this a "variable list" because they are technically not considered to be variables but rather parameters. And sometimes, we call them formal parameters since they are really just formal placeholders for actual values (like the numbers 5 and 10) that will eventually be passed into the method.
- The method signature of a method is the name of the method along with its parameter list. So the method signature of the computeAreaTriangle method above is
computeAreaTriangle(int base, int height)
and really the formal parameter names are not that important as far as the method signature goes so you can also say that the method signature is
computeAreaTriangle(int, int)
- Methods should generally be made public especially in this introductory programming course. So the method header should always begin with the keyword public. While it is possible to also use private and protected as scope modifiers for methods. And, by default, if a scope modifier keyword is not used in a method header, than the scope access is considered to be package level that typically gives a class access to any method within a class file contained in the same folder or directory as the file.
- The use of the data type double in the method header is called the method's return type. If a method includes a return statement, then the data type (usually int, double, or String in this AP Computer Science course) must be typed in the header. If there is no return statement (or the return statement is empty as in return; ) then the keyword void must be used. Examples,
public int computeSum(int num1, int num2)
{
return num1 + num2;
}
public double computeTax(double price, double taxRate)
{
return price * taxRate;
}
public String makeFancyName(String name)
{
return "**** " + name + " ******";
}
public void displayFancyName()
{
System.out.println("**** " + name + " ******");
}
public void displayFancyName()
{
System.out.println("**** " + name + " ******");
return; // this statement is optional since no value is actually being returned
}
- Methods that are defined (i.e. typed out) and included in the same class file where they are meant to be used are often referred to as static methods. The keyword static must be used in their header. So the keyword static could have been used in many of the examples above as in
public static double computeAreaTriangle(int base, int height)
{
return base * height / 2.0;
}
At this time in our AP Computer Science course do not worry about this use of the keyword static. You will understand when to use it or not later. For now, see the instructor if you have any questions in exercises or programming assignments.
Objective #3: Call methods that are implemented in the same class file.
- A call statement is a statement that makes use of a method. To make use of a method means to call a method. Examples are
System.out.println(Math.pow(3, 2));
area = computeAreaTriangle(10, 2);
displayFancyName("Smith");
- Methods are typically typed out and defined in a class file below the main method. The following program begins with the execution of the main method. But the 3 call statements in the main method invoke and execute the other three methods. It doesn't matter in what order the methods are typed out in the class. The call statements execute in the order that they are listed.
public class MethodsDemo1
{
public static void main(String[] args)
{
drawHead();
drawBody();
drawLegs();
}// end of main
public static void drawHead()
{
System.out.println("0");
}
public static void drawBody()
{
System.out.println("I");
}
public static void drawLegs()
{
System.out.println("/\\");
}
}// end of MethodsDemo1
Objective #3: Pass parameters to methods.
- You can pass parameters to methods with a call statement. In the following example, an int and a String are passed from one method to another.
public class MethodsDemo2
{
public static void main(String[] args)
{
drawMan(3, "Bob");
}// end of main
public static void drawMan(int num, String name)
{
for (int i = 0; i < num; i++)
{
drawHead();
drawBody();
drawLegs();
}// end of for
System.out.println(name);
}// end of drawMan
public static void drawHead()
{
System.out.println("0");
}// end of drawHead
public static void drawBody()
{
System.out.println("I");
}// end of drawBody
public static void drawLegs()
{
System.out.println("/\\");
}// end of drawLegs
}// end of MethodsDemo2
Notice the use of inline "end of" comments that are useful in keeping track of where one method, loop, or class ends and another one begins. Also notice that blank lines that are placed around loops and methods to make the code more readable. The value 3 in the call statement automatically matches up with the formal parameter num in the drawMan method header while the string literal "Bob" matches up with the formal parameter name.
Objective #4: Return values from methods.
- The methods above are examples of void methods because they have the return type void. They do not return values.
- In the following examples, each method returns a value such as an int, double, boolean or String.
public class MethodsDemo3
{
public static void main(String[] args)
{
int sum = 0;
sum = addThem(3, 4);
System.out.println(addThem(5, 6));
int x = 7, y = 8;
System.out.println(addThem(x, y));
System.out.println(isEven(5));
System.out.println(firstLetter("Wyomissing"));
System.out.println(addThem(addThem(1, 2), addThem(3, 4)));
System.out.println(getRandomDecimalNumber());
}
public static int addThem(int num1, int num2)
{
return num1 + num2;
}
public static boolean isEven(int num)
{
if (num % 2 == 0) // checking to see if num is evenly divisible by 2 or not
{
return true;
}
return false;
}
public static String firstLetter(String word)
{
return word.substring(0, 1);
}
public static double getRandomDecimalNumber()
{
return Math.random(); // returns a random decimal number between 0.0 and .9999
}
}// end of MethodsDemo3
Even though you may not have studied if statements or the random method, the methods above work as their names imply. The data type that is returned by each method is typed after the keyword static and before the name of the method.
Objective #5: Write your own user-defined static methods.
- It is proper style to begin the names of methods
with lowercase letters as in computeTax or displayFancyName.
- To implement a method means
to type code into the body of that method so the method knows how to execute when
it is called.
Objective #6: Make use of overloaded methods.
- It is possible to include two methods with the same
name in a class. When this occurs the methods are called overloaded methods. Methods are overloaded when they have the same name but a different parameter lists.
- For example, you can have one method in a Bug class
named move that
accepts no parameters and another method that is also named move but that
accepts one parameter as in the following example.
public void move()
and
public void move(int amount)
Or two methods could have the same number of parameters but with a different order of parameter data types as in
public void move(int x, double y)
and
public void move(double x, int y)
- Two parameter lists can be different from each other by:
- having a different number
of parameters,
- having
parameters
with
different data types, or
- by having the same number of parameters
but with
the data
types in a different order.
- So the following methods could both be used in a Bug class even though they have the same name. Since they have different parameter lists, they are treated as two different methods.
public void move()
{
myX = myX + 5;
}
public void move(int amount)
{
myX = myX + amount;
}
Even though they have different return types, the following methods are considered to have the same parameter lists so they would cause a compile error and are not examples of properly overloaded methods.
public void move(int amount, int start)
{
myX = start + amount;
}
public int move(int amount, int start)
{
return myX + amount + start;
}
- Here are more examples of pairs of overloaded methods:
int move(int amount)
int move(double amount)
int move(int amount, int speed)
int move(int amount, double speed)
int move(double amount, int speed)
int move(int amount, double speed)
- Here are examples of methods that are not properly overloaded
int move1(int amount, int speed) ' this does compile
int move2(int amount, int speed)
double move1(int amount, int speed)
int move2(int amount, int speed)
int move1(int x, int y)
int move1(int a, int b)
Objective #7: Use local variables within methods.
- Local variables can be declared and used
within individual methods in a class as in this haveBirthday method:
public static double computeTax(double price, double taxRate)
{
double total = 0.0;
total = price * taxRate;
return total;
}
Clearly though the use of the local variable num is a waste in this example
since the single statement myAge++; would
have sufficed.
public static double computeTax(double price, double taxRate)
{
return price * taxRate;
}
- A local variable MUST be initialized when it is declared inside of a method.
For example, the method
public static double computeTax(double price, double taxRate)
{
double total; // compile error occurs
total = price * taxRate;
return total;
}
will cause a compile error since total was not
initialized. Unlike some other computer languages like Visual Basic, Java does not always initialize
variables to zero. (Though Java does initialize special kinds of variables called instance variables to zero but more about that later in this course.)
- A local variable only has a scope of the method in
which it is declared. That is, you cannot refer to a local variable in another
method.
public static double computeTax(double price, double taxRate)
{
double total = 0.0;
total = price * taxRate;
return total;
}
public static double computeShipping(double price, double shippingRate)
{
total = total + price * shippingRate; // compile error since total is not declared in this method
return total;
}
- Once the method
has executed and when the compiler reaches the method's closing curly brace,
all of the method's local variables are discarded and "garbage collected". Garbage collection is an aspect of Java in which the memory occupied by unused
variables is automatically reclaimed by the operating sysem as a program executes.