Title: Java Programming: From Problem Analysis to Program Design, 4e
1Java Programming From Problem Analysis to
Program Design, 4e
- Chapter 7
- User-Defined Methods
2Chapter Objectives
- 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
3Chapter Objectives (continued)
- 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
4Predefined Classes
- Methods already written and provided by Java
- Organized as a collection of classes (class
libraries) - To use import package
- Method type data type of value returned by method
5Predefined Classes (continued)
6Predefined Classes (continued)
7Predefined Classes (continued)
8Predefined Classes (continued)
9class Character (Package java.lang)
10class Character (Package java.lang) (continued)
11class Character (Package java.lang) (continued)
12Syntax Value-Returning Method
13User-Defined Methods
- Value-returning methods
- Used in expressions
- Calculate and return a value
- Can save value for later calculation or print
value - modifiers public, private, protected, static,
abstract, final - returnType type of the value that the method
calculates and returns (using return statement) - methodName Java identifier name of method
14Syntax
- Syntax formal parameter list
- -The syntax of the formal parameter list is
-
- Method call
- -The syntax to call a value-returning method is
15Syntax (continued)
- Syntax actual parameter list
- -The syntax of the actual parameter list is
- Syntax return statement
- -The return statement has the following
syntax - return expr
16Equivalent Method Definitions
public static double larger(double x, double
y) double max if (x gt y)
max x else max y return
max
1717
Java Programming From Problem Analysis to
Program Design, 4e
1818
Java Programming From Problem Analysis to
Program Design, 4e
19Equivalent Method Definitions (continued)
- public static double larger(double x, double y)
-
- if (x gt y)
- return x
- else
- return y
-
20Equivalent Method Definitions (continued)
- public static double larger(double x, double y)
-
- if (x gt y)
- return x
-
- return y
-
21The int variable num contains the desired sum to
be rolled
21
Java Programming From Problem Analysis to
Program Design, 4e
22Palindrome Number
- Palindrome integer or string that reads the same
forwards and backwards - The method isPalindrome takes a string as a
parameter and returns true if the string is a
palindrome, false otherwise
23Solution isPalindrome Method
public static boolean isPalindrome(String str)
int len str.length()
int i, j j len - 1 for (i 0 i lt
(len - 1) / 2 i) if
(str.charAt(i) ! str.charAt(j))
return false j--
return true
24Flow of Execution
- Execution always begins with the first statement
in the method main - User-defined methods execute only when called
- Call to method transfers control from caller to
called method - In method call statement, specify only actual
parameters, not data type or method type - Control goes back to caller when method exits
25Programming Example Largest Number
- Input set of 10 numbers
- Output largest of 10 numbers
- Solution
- Get numbers one at a time
- Method largest number returns the larger of two
numbers - For loop calls method largest number on each
number received and compares to current largest
number
26Solution Largest Number
static Scanner console new Scanner(System.in)
public static void main(String args)
double num double max int count
System.out.println("Enter 10 numbers.") num
console.nextDouble() max num
for (count 1 count lt 10 count)
num console.nextDouble() max
larger(max, num) System.out.println("
The largest number is "
max)
27Sample Run Largest Number
- Sample Run
- Enter 10 numbers
- 10.5 56.34 73.3 42 22 67 88.55 26 62 11
- The largest number is 88.55
28Void Methods
- Similar in structure to value-returning methods
- Call to method is always stand-alone statement
- Can use return statement to exit method early
29Void Methods with Parameters Syntax
30Void Methods with Parameters Syntax (continued)
31Primitive Data Type Variables as Parameters
- A formal parameter receives a copy of its
corresponding actual parameter - If a formal parameter is a variable of a
primitive data type - Value of actual parameter is directly stored
- Cannot pass information outside the method
- Provides only a one-way link between actual
parameters and formal parameters
32Reference Variables as Parameters
- If a formal parameter is a reference variable
- Copies value of corresponding actual parameter
- Value of actual parameter is address of the
object where actual data is stored - Both formal and actual parameter refer to same
object
33Uses of Reference Variables as Parameters
- Can return more than one value from a method
- Can change the value of the actual object
- When passing address, would save memory space and
time, relative to copying large amount of data
34Reference Variables as Parameters type String
35Reference Variables as Parameters type String
(continued)
36Reference Variables as Parameters type String
(continued)
37Reference Variables as Parameters type String
(continued)
38Reference Variables as Parameters type String
(continued)
String str "Hello" //Line 5
38
Java Programming From Problem Analysis to
Program Design, 4e
39Reference Variables as Parameters type String
(continued)
stringParameter(str) //Line 7
39
Java Programming From Problem Analysis to
Program Design, 4e
40Reference Variables as Parameters type String
(continued)
pStr "Sunny Day" //Line 14
40
Java Programming From Problem Analysis to
Program Design, 4e
41Reference Variables as Parameters type String
(continued)
Variables before the statement in Line 8 executes
42- The class StringBuffer contains the method
append, which allows you to append a string to an
existing string, and the method delete, which
allows you to delete all the characters of the
string - The assignment operator cannot be used with
StringBuffer variables you must use the operator
new (initially) to allocate memory space for a
string
4343
Java Programming From Problem Analysis to
Program Design, 4e
4444
Java Programming From Problem Analysis to
Program Design, 4e
4545
Java Programming From Problem Analysis to
Program Design, 4e
4646
Java Programming From Problem Analysis to
Program Design, 4e
4747
Java Programming From Problem Analysis to
Program Design, 4e
48- Primitive Type Wrapper Classes as Parameters
- If a formal parameter is of the primitive data
type and the corresponding actual parameter is a
variable, then the formal parameter cannot change
the value of the actual parameter - Only reference variables can pass values outside
the method (except, of course, for the return
value) - Corresponding to each primitive data type, Java
provides a class so that the values of primitive
data types can be wrapped in objects - The class Integer does not provide a method to
change the value of an existing Integer object - The same is true of other wrapper classes
49- Primitive Type Wrapper Classes as Parameters
(continued) - If we want to pass a String object as a parameter
and also change that object, we can use the class
StringBuffer - Java does not provide any class that wraps
primitive type values in objects and when passed
as parameters changes their values - If a method returns only one value of a primitive
type, then you can write a value-returning method - If you encounter a situation that requires you to
write a method that needs to pass more than one
value of a primitive type, then you should design
your own classes - Appendix D provides the definitions of such
classes and shows how to use them in a program
49
Java Programming From Problem Analysis to
Program Design, 4e
50Scope of an Identifier within a Class
- Local identifier identifier declared within a
method or block, which is visible only within
that method or block - Java does not allow the nesting of methods you
cannot include the definition of one method in
the body of another method - Within a method or a block, an identifier must be
declared before it can be used a block is a set
of statements enclosed within braces
51Scope of an Identifier within a Class (continued)
- A methods definition can contain several blocks
- The body of a loop or an if statement also form a
block - Within a class, outside of every method
definition (and every block), an identifier can
be declared anywhere
52Scope of an Identifier within a Class (continued)
- 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 - For example, in the method definition on the next
slide, the second declaration of the variable x
is illegal
53Scope of an Identifier within a Class (continued)
- public static void illegalIdentifierDeclaration()
-
- int x
-
- //block
-
- double x //illegal declaration,
- //x is already declared
- ...
-
54Scope Rules
- Scope rules of an identifier declared within a
class and accessed within a method (block) of the
class - An identifier, say X, declared within a method
(block) is accessible - Only within the block from the point at which it
is declared until the end of the block - By those blocks that are nested within that block
55Scope Rules (continued)
- Suppose X is an identifier declared within a
class and outside of every methods definition
(block) - If X is declared without the reserved word static
(such as a named constant or a method name), then
it cannot be accessed in a static method - If X is declared with the reserved word static
(such as a named constant or a method name), then
it can be accessed within a method (block),
provided the method (block) does not have any
other identifier named X
56Scope Rules (continued)
- Example 7-11public class ScopeRules
-
- static final double rate 10.50
- static int z
- static double t
- public static void main(String args)
-
- int num
- double x, z
- char ch
- //...
-
- public static void one(int x, char y)
-
- //...
-
57Scope Rules (continued)
- public static int w
- public static void two(int one, int z)
-
- char ch
- int a
-
- //block three
-
- int x 12
- //...
- //end block three
- //...
-
58Scope Rules Demonstrated
59Scope Rules Demonstrated (continued)
60Method Overloading An Introduction
- Method overloading more than one method can have
the same name - Two methods are said to have different formal
parameter lists if both methods have - A different number of formal parameters, or
- If the number of formal parameters is the same,
then the data type of the formal parameters, in
the order you list, must differ in at least one
position
61Method Overloading
- public void methodOne(int x)
- public void methodTwo(int x, double y)
- public void methodThree(double y, int x)
- public int methodFour(char ch, int x,
- double y)
- public int methodFive(char ch, int x,
- String name)
- These methods all have different formal parameter
lists
62Method Overloading (continued)
- public void methodSix(int x, double y,
- char ch)
- public void methodSeven(int one, double u,
- char firstCh)
- The methods methodSix and methodSeven both have
three formal parameters and the data type of the
corresponding parameters is the same - These methods all have the same formal parameter
lists
63Method Overloading (continued)
- Method overloading creating several methods,
within a class, with the same name - The signature of a method consists of the method
name and its formal parameter list - Two methods have different signatures if they
have either different names or different formal
parameter lists - Note that the signature of a method does not
include the return type of the method
64Method Overloading (continued)
- The following method headings correctly overload
the method methodXYZ - public void methodXYZ()
- public void methodXYZ(int x, double y)
- public void methodXYZ(double one, int y)
- public void methodXYZ(int x, double y,
- char ch)
65Method Overloading (continued)
- public void methodABC(int x, double y)
- public int methodABC(int x, double y)
- Both these method headings have the same name and
same formal parameter list - These method headings to overload the method
methodABC are incorrect - In this case, the compiler will generate a syntax
error - Notice that the return types of these method
headings are different
66Programming Example Data Comparison
- Input data from two different files
- Data format course number followed by scores
- Output course number, group number, course
average - Solution
- Read from more than one file, write output to
file - Generate bar graphs
- User-defined methods and re-use (calculateAverage
and printResult) - Parameter passing
67Programming Example Data Comparison (continued)
- Sample Output
- Course No Group No Course Average
- CSC 1 83.71
- 2 80.82
- ENG 1 82.00
- 2 78.20
- HIS 1 77.69
- 2 84.15
- MTH 1 83.57
- 2 84.29
- PHY 1 83.22
- 2 82.60
- Avg for group 1 82.04
68Programming Example Data Comparison (continued)
69Chapter Summary
- Predefined methods
- User-defined methods
- Value-returning methods
- Void methods
- Formal parameters
- Actual parameters
- Flow of Execution
70Chapter Summary (continued)
- Primitive data type variables as parameters
- One-way link between actual parameters and formal
parameters (limitations caused) - Reference variables as parameters
- Can pass one or more variables from a method
- Can change value of actual parameter
- Scope of an identifier within a class
- Method overloading