11 Chapter 5 METHODS CONT’D. 22 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference...
-
Upload
anthony-wade -
Category
Documents
-
view
224 -
download
0
Transcript of 11 Chapter 5 METHODS CONT’D. 22 MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference...
11
Chapter 5METHODS CONT’D
22
MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method
• Objects are passed by reference in Java.
• This means that when you pass an argument of a non-primitive type (a class type) it is actually the address of the object that is passed.
• The parameter variable that receives this address/reference will reference the object that was the argument.
• A copy of the object is not created.
• The method that receives the reference to the object has access to the original object.
33
MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method /** A void method that displays a student's letter grade along with a message. @param name The name of the student @param grade The character representing the student's letter grade*/
public static void displayGrade(String name, char grade){
System.out.println("\nThe grade assigned for " + name + " is " + grade + ".");
if (grade == 'A'){System.out.println("Fantastic!");}else if (grade == 'B'){System.out.println("Great job!");}return;
}
44
MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method Example:
The statement highlighted below calls the method displayGrade passing the address of the object that contains the name of the student as the first argument and the value stored in the variable letterGrade as the second argument. We say that the parameter variable name references the object that contains the name of the student, because it has the address of the object, just like studentName does in the calling method.
displayGrade(studentName, letterGrade);
public static void displayGrade(String name, char grade)
addressstudentName
addressname
Heap
A String object
copy of argumentgrade
The local variables of the methods are stored on the stack .
letterGradeactual data
item
55
MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method
• If the object passed as an argument is a String, you do not need to be concerned that the method will change the String.
• In Java, strings are immutable, which means they cannot be changed.
66
MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method
At the beginning of changeString
String myString = "Go Stars!";
changeString(myString); // Call to changeString
public static void changeString(String anotherString){
anotherString = "Go Ducks!";
return;}
address
Go Stars!
A String object
myString
addressanotherString
77
MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method
At the end of changeString
String myString = "Go Stars!";
changeString(myString); // Call to changeString
public static void changeString(String anotherString){
anotherString = "Go Ducks!"; // Assigns a new address to anotherString
return;}
address
Go Stars!
A String object
myString
addressanotherString
Go Ducks!
A String object
Note: the original
String is not changed.
88
MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method
The method changeString depicted in the previous slides creates a new String object to hold the string Go Ducks! The address of this String object is assigned to the reference variable named anotherString.
99
MORE ON PASSING ARGUMENTS TO A METHOD Passing an Object Reference as an Argument to a Method
• Remember that the concatenation operator, the nextLine method of a Scanner object, the showInputDialog method of the JOptionPane class, and the toUpperCase and toLowerCase methods of the String class all create String objects.
• The assignment operator copies the address of the String object when it is used on strings. It does not copy a String.
1010
MORE ON PASSING ARGUMENTS TO A METHOD Using the @param Tag in a Documentation Comment for a Method that Accepts Arguments
• When you use the @param tag in a documentation comment describing a method, the description of the parameter variable that follows this tag is included in the documentation created by the javadoc utility program.
• The description of the parameter variables must appear after the general description of the method.
1111
MORE ABOUT LOCAL VARIABLES The Lifetime of Local Variables
• A method's local variables and parameters exist only when the method is executing. This is often called the lifetime of these variables.
• When the method begins executing, its local and parameter variables are created in memory, and when the method's execution ends these variables are destroyed.
1212
MORE ON VALUE-RETURNING METHODS
• Methods can return a value of any data type.
For example, in the program DemoMethods.java the method named getGrade returned a value of type int to the code that called it and the method named assignLettGrade returns a value of type char.
1313
MORE ON VALUE-RETURNING METHODS
• It is common to write methods that test an argument or arguments to see if some condition exists and return a boolean value to indicate whether the condition does or does not exist.
1414
MORE ON VALUE-RETURNING METHODS
/** A method that determines if the character that is passed in as its argument is a digit. @param character The character to be tested @return true if the character is a digit, false otherwise*/
public static boolean isDigit(char character){
boolean aDigit = false;
if (character >= '0' && character <= '9'){
aDigit = true;}
return aDigit;}
1515
MORE ON VALUE-RETURNING METHODS Using the @return Tag in the Documentation Comment
for a Value-Returning Method • You can use the @return tag in a documentation comment
describing a method to provide a description of the value returned by the method.
• The javadoc utility program will create a section in the documentation for the method under a heading Returns: that includes the words following the @return tag.
• The description of the return value must appear after the general description of the method.
1616
MORE ON VALUE-RETURNING METHODS
Returning a Reference to an Object
• A method can return a reference to an object.
1717
MORE ON VALUE-RETURNING METHODS
Returning a Reference to an Object
For example, the method shown below from DemoMethodsWRefVar.java returns a reference to an object of the String class.
public static String getName(Scanner keyboard){
String name;
System.out.print("Enter the student's name ");name = keyboard.nextLine( );
while (name.length( ) == 0) // While the name is the empty string{
System.out.println("\nError, invalid name entered.");System.out.print("Enter the student's name ");name = keyboard.nextLine( );
}
return name;}
1818
MORE ON VALUE-RETURNING METHODS
Returning a Reference to an ObjectThe Lifetime of an Object
• Objects are created in a part of memory known as the heap. They are not created on the stack like variables of primitive data types.
• Objects are not automatically destroyed when the method in which they were created terminates.
• The lifetime of a object is until the object is no longer referenced by an reference variable.
1919
MORE ON VALUE-RETURNING METHODS
Returning a Reference to an Object
• When the method getName ends its execution in DemoMethodsWRefVar.java, the local variable name is destroyed, but the String object that was created is not automatically destroyed.
• We can return the address of this object and this value can be stored in another reference variable that can be used to access the object.
2020
MORE ON VALUE-RETURNING METHODS
Returning a Reference to an Object
*** See the program DemoMethodsWRefVar.java on webct
2121
PROBLEM SOLVING WITH METHODS
• When we develop our code incrementally, we often write code that is used only during the development of the program and does not appear in the final program.
2222
PROBLEM SOLVING WITH METHODS
• A driver is a dummy method that can be used to test a called method.
• The driver calls the method passing it arguments that are used to test the logic of the method.
• If the called method returns a value the driver usually displays this value on the screen.
• Quite often a driver uses a loop to call the method over and over. It might be a loop that lets the user repeatedly enter test cases or it might be some sort of count-controlled loop(s) that calls the method with arguments in a specific range.
2323
PROBLEM SOLVING WITH METHODS
• To test a method that calls other methods, it is often useful to create stubs for the called methods.
• A stub is a dummy method that can be called by the method being tested.
• A stub usually displays a message indicating that it has been called, so that the programmer can verify that the method is called as expected.
• A stub for a method that accepts arguments usually displays the arguments on the computer screen so the programmer can ensure that the values are being passed properly.
• A stub for a value-returning method usually returns a test value so that the programmer can test the calling method's use of the return value.
2424
PROBLEM SOLVING WITH METHODS
Problem:
Suppose we wanted to write a program that gets the social security number, first name, last name, and hourly pay rate of an unspecified number of employee's from the user and stores these in a file selected by the user. The data items should be stored in the file in the following order: social security number, last name, first name, and hourly pay rate. One newline character must separate the individual data items for an employee in the file and one newline character must separate one employee's hourly pay rate from the next employee's social security number in the file.
2525
PROBLEM SOLVING WITH METHODS
The program TestgetHourlyRate.java was written to test the method getHourlyRate. The main method is a driver. It calls the method getHourlyRate so that we can test the logic of this method. This main method is not the main method of our final program.
2626
PROBLEM SOLVING WITH METHODS
The program PartOfSaveEmployeeData.java was written to test the logic of the main method. Several of the methods that have not been completed at this point are represented by stubs.
2727
PROBLEM SOLVING WITH METHODS
***See the program SaveEmployeeData.java on webct