Chapter 7 User-Defined Methods Chapter Overview In this chapter, students will learn more about predefined methods and using them in Java programs as well as user-defined methods. Several methods can be put together to form larger programs. Chapter Objectives In this chapter, students will: · · · · · · · Understand how methods are used in Java programming Learn about standard (predefined) methods and discover how to use them in a program Learn about user-defined methods Examine value-returning methods, including actual and formal parameters Explore how to construct and use a value-returning, user-defined method in a program Learn how to construct and use user-defined void methods in a program Explore variables as parameters · · Learn about the scope of an identifier Become aware of method overloading Introduction In Java, there are predefined methods that are already written and provided and user-defined methods, methods that you create. While working on one method, you can focus on just that part of the program and construct it, debug it, and perfect it. Different people can work on different methods simultaneously. If a method is needed in more than one place in a program, or in different programs, you can write it once and use it many times. Using methods greatly enhances the program’s readability because it reduces the complexity of the method main. Predefined Methods In Java, predefined methods are organized as a collection of classes, called class libraries. The class Math contained in the package java.lang contains mathematical methods. The method type is the data type of the Chap7_1 value returned by the method. Some predefined methods in the class Math are: Math.abx(x) Math.ceil(x) Math.exp(x) Math.floor(x) Math.log(x) Math.max(x, y) Math.min(x, y) Math.pow(x, y) Math.round(x) Math.sqrt(x) Math.cos(x) Math.sin(x) Math.tan(x) The class Character, also in the package java.lang contains the following methods: Character.isDigit(ch) Character.isLetter(ch) Character.isLowerCase(ch) Character.isUpperCase(ch) Character.isSpaceChar(ch) Character.isWhitespace(ch) Character.toLowerCase(ch) Character.toUpperCase(ch) In general, to use predefined methods of a class in a program, you must import the class from the package containing the class. By default Java automatically imports classes from the package java.lang. Therefore, if you use a method from the class Math or Character you do not need to explicitly import these classes in your program. User-Defined Methods There are two types of user-defined methods: value-returning methods and void methods. Value-returning methods, used in expressions, calculate and return a value. They methods are usually used to save the value for further calculation, use the value in a calculation or to print the value. To use these Chap7_2 methods you must know: the heading of the method (the name of the method, the number of parameters (if any), the data type of each parameter, and the type of the method), and the body of the method (code required to accomplish the task). In other words, you must know the definition of the method. For predefined methods you only need to know the heading for ones you create, you must know the entire definition. The variable declared in the heading, within the parentheses, of the method is called the formal parameter of the method. The actual parameter is the variable or expression listed in a call to the method. The syntax of a value-returning method is: modifier(s) returnType methodName(formal parameter list) { statements } The modifier(s) indicates the visibility of the method; where in a program the method can be used (called). Some of the modifiers are public, private, protected, static, abstract, and final. If you include more than one modifier, they must be separated with spaces. You can select one modifier among public, protected, and private. The modifier public specifies that the method can be called outside the class, and the modifier private specifies that the method cannot be used outside the class. Similarly, you can choose one of the modifiers static or abstract. The returnType is the type of value that the method calculates and returns. This type is also called the type of the value-returning method. The methodName is a Java identifier, giving a name to the method, and statements enclosed between curly braces form the body of the method. The syntax of the formal parameter list is: dataType identifier, dataType identifier, … The syntax to a value-returning method call is: methodName(actual parameter list) If the parameter list is empty the parentheses remain empty. The syntax of the actual parameter list is: Expression or variable, expression or variable, … Chap7_3 In a method call, the number of actual parameters, together with their data types, must match the formal parameters in the order given. Once a value-returning method computes the value, the method returns this value via the return statement. The syntax for the return statement uses reserved word return and is: return expr; where expr (a variable, constant, or expression) is evaluated and returned. The data type of the value that expr computes must match the method type. When a return statement executes in a method, the method immediately terminates and the control goes back to the caller. Programming Example: Palindrome Number An integer is a palindrome if it reads backwards and forwards the same way. The input to this program is an integer (positive or negative). The output to this program is a message indicating whether the integer is a palindrome. The solution to this program consists of writing a method isPalindrome. The method returns a Boolean value. Its only parameter is the integer string that needs to be checked. The body of the method gets the length of the string and using a for loop compares the first half of the string to the last half one character at a time. If the first and last character don’t match the method returns false. Otherwise, it increments the position of the first character being checked and decrements the position of the last character checked and compares them. This is done until the characters no longer match. If they match till the end of the loop the method returns true. Flow of Execution When the program executes, the execution always begins with the first statement in the method main. User-defined methods execute only when they are called. A call to a method transfers control from the caller to the called method. In a method call statement, you specify only the actual parameters, not their data type or the method type. When a method exits, the control goes back to the caller. Programming Example: Largest Number Chap7_4 The input to this program is a set of 10 numbers and the output is the largest of the numbers. The program can be easily modified to accommodate any set of numbers. The solution to this program consists of writing a method that compares two numbers and returns the larger of the two. This method is then called in a for loop in the main method of the program. The first number entered is stored as the maximum, and as each new number is entered it is compared to the current maximum. The maximum is then replaced if the new number is larger than the current maximum. Void Methods Void methods do not have a data type. The syntax for the method without parameters is as follows: modifier(s) void methodName() { statements } A call to a void method is a stand-alone statement. The method call for void methods, within the class has the following syntax: methodName(); void methods without parameters are often used for displaying information about the program or for printing statements. The syntax for a void method with parameters is as follows: modifier(s) void methodName(formal parameter list) { statements } where the formal parameter list has the syntax: dataType variable, dataType variable, … The method call would have the syntax: Chap7_5 methodName(actual parameter list); Where the actual parameter list would have the syntax: expression or variable, expression or variable, … Quick Quiz 1. True or False: Void methods do not have a type. Answer: True 2. A(n) ____ parameter is a variable declared in the method heading. Answer: formal 3. True or False: To use the method Math.sqrt(x) you must import the package java.lang. Answer: False 4. True or False: Void methods are always stand-alone statements. Answer: True 5. An integer or string is a(n) ____ if it reads the same forwards and backwards. Answer: palindrome Primitive Data Type Variables as Parameters When a method is called, the value of the actual parameter is copied into the corresponding formal parameter. If a formal parameter is a variable of a primitive data type, then after copying the value of the actual parameter, there is no connection between the formal parameter and the actual parameter; a formal parameter of the primitive type cannot pass any result back to the calling method. When the method executes, any changes made to the formal parameters do not in any way affect the actual parameters. The actual parameter has no knowledge of what is happening to the formal parameter. Thus, formal parameters of the primitive data types cannot pass information outside the method. Formal parameters of the primitive data types provide only a one-way link between actual parameters and formal parameters. Chap7_6 Reference Variables as Parameters A reference variable contains the address (memory location) of the actual data; both the formal and the value parameters refer to the same object. Therefore, reference variables can pass one or more values from a method and can change the value of the actual parameter. Reference variables, as parameters are useful in three situations: 1. When you want to return more than one value from a method 2. When the value of the actual object needs to be changed 3. When passing the address would save memory space and time, relative to copying a large amount of data When a method is called, memory for its formal parameters and local variables is allocated in the method data area. The value of the actual parameter is copied into the memory cell of its corresponding formal parameter. In the case of reference variables of the type String, we can use the assignment operator to allocate memory space to store a string and assign the string to a String variable. If you pass a String variable (a reference variable of the String type) as a parameter to a method, and within the method you use the assignment operator to change the string, the string assigned to the actual parameter does not change; a new string is assigned to the formal parameter. If you want to pass strings as parameters to a method and want to change the actual parameter, you can use the class StringBuffer, where strings assigned to StringBuffer variables can be altered using various methods provided to manipulate strings (e.g. append, delete). Scope of an Identifier Within a Class The scope of an identifier refers to what other parts of the program can “see” an identifier; where it is accessible (visible). A local identifier is an identifier declared within a method or block that can be accessed only by code within that same method or block. Java does not allow the nesting of methods. That is, you cannot include the definition of one method in the body of another method. Within a class, an identifier is accessible throughout the class, with the exception that a static method cannot access nonstatic identifiers. The identifier declared within a block is accessible: 1. Only within the block from the point at which it is declared until the end of the block. Chap7_7 2. By those blocks that are nested within that block if the nested block does not have an identifier with the same name as that of the outside block (the block that encloses the nested block). Within a method, an identifier used to name a variable in the outer block of the method cannot be used to name any other variable in an inner block of the method. Within a class, any method can call any other method, with the exception that a static method cannot call a nonstatic method. A variable can be declared in the initialization statement of the for statement; the scope of the variable is limited only to the body of the loop. Method Overloading: An Introduction Method overloading is creating several methods, within a class, with the same name. If several methods within a class have the same name, every method must have a different number of formal parameters, or if the number of formal parameters is the same, then the data type of the formal parameter, in the order listed, must differ in at least one position. The types of parameters determine which method to execute. Programming Example: Data Comparison The input to this program is two different data files each with a course number followed by a series of scores. The output is a file containing the course numbers, group numbers, and the course average for each group in each course. The solution to this program consists of reading data from two different files and printing the results to an output file. It also contains the user-defined methods calculateAverage and printResult. Quick Quiz 1. ____ variables are useful when you want to return more than one value from a method. Answer: Reference 2. True or False: It is possible to create several methods with the same name in a single class. Answer: True 3. A(n) ____ identifier is an identifier declared within a method or block that can be accessed only by code within that same method or block. Chap7_8 Answer: local 4. True or False: A method can be defined within the body of another method. methods. Answer: False This is known as nesting 5. True or False: In the case of reference variables of the type String, we can use the assignment operator to allocate memory space to store a string and assign the string to a String variable. Answer: True Discussion Questions Some interesting topics of discussion in Chapter Seven include: Ø Ø Ø Discuss examples of user-defined methods. Discuss common errors when identifying the scope of identifiers. Discuss how to overload methods correctly and when overloading is useful. Projects to Assign 1. Assign odd Exercises. 2. Assign Programming Exercises 14 or 15. material. These are fairly extensive, but cover a lot of important Key Terms Ø Actual parameter: a variable or expression listed in a call to a method. Ø Class libraries: organized collection of classes. Ø Formal parameter: a variable declared in the method heading. Ø Local identifier: an identifier declared within a method or block that can be accessed only by code within that same method or block. Ø Local variables: variables declared in the body of the method. Ø Method type: data type of the value returned by the method. Ø Modules: another name for methods. Ø Palindrome: integer or string that reads the same forwards and backwards. Ø Parameters: arguments of a method. Chap7_9 Ø Ø Predefined methods: methods that are already written and provided by Java. Scope: refers to what other parts of the program can “see” an identifier. Ø Ø Ø User-defined methods: methods that the programmer creates. Value-returning methods: methods that have a return type. Void methods: methods that do not have a return type. Chap7_10