Chapter 5 Chapter 5 Methods 1 2 Contents Introduction to Methods Passing Arguments to a Method More about Local Variables Returning a Value from a Method Problem Solving with Methods 2 3 1 Introductio.
Trang 1Chapter 5
Methods
Trang 2Contents
Trang 31 Introduction to Methods
performs a specific task
such as
Trang 41 Introduction to Methods
into small manageable pieces
all of the statements, several small methods that each solve a specific part of the problem can be written
because a large problem is divided into several
problems
Trang 61 Introduction to Methods
simplify programs
a program, a method can be written once and
then be executed anytime it is needed
reuse.
Trang 8void Methods and
Value-Returning Methods
task, but also sends a value back to the code that called it
Trang 9Defining a void Method
which consists of two general parts:
when the method is executed
public static void main(String[] args)
{
System.out.println(“Hello World!”);
} Header
Body
Trang 10Defining a void Method
public static void displayMessage ()
{
System.out.println(“Hello from the displayMessage method.”);
}
Method Modifiers:
- public: The method is publicly available to code outside the class
- static: The method belongs to the class, not a specific object.
Return Type:
- void: The method is a void method, and does not return a value.
Method Name: A descriptive name that can describes the function of the method.
Parentheses:
- The method name is always followed by a set of parentheses.
- List of arguments will appear inside the parentheses.
Method Modifiers
Return Type
Method Name
Parentheses The method header is never terminated with a semicolon.
Trang 11Calling a Method
program starts
statements
that method and executes the statements in its
body
displayMessage();
Method call statement:
- The statement is simply the name of the method followed by a set of parentheses.
- The method modifiers and the void return type are not written.
Trang 12Calling a Method
Trang 13Branching in the SimpleMethod.java Program
public static void main(String[] args)
Trang 14Calling a Method
Trang 15Calling a Method
his annual salary and credit rating The program determines whether the user qualifies for a credit card One of two void methods, qualify or
noQualify, is called to display a message
Credit rating:
The user qualifies for a credit card if his salary is not less than $20,000 and his credit rating is not less than 7
Trang 16Calling a Method
Trang 17Calling a Method
Trang 19Hierarchical Method Calls
Trang 20Hierarchical Method Calls
Trang 21Using Documentation Comments
with Methods
comments that appear just before the method's
definition
of the method's purpose
with /** and end with */ These types of
comments can be read and processed by a
program named javadoc which produces
attractive HTML documentation
Trang 232 Passing Arguments to a
Method
to as a parameter, is a special variable that holds
a value being passed into a method
public static void displayValue(int num)
{
System.out.println(“The value is “ + num);
}
integer value as an argument
Trang 24various arguments passed:
displayValue(x);
displayValue(x * 4);
The argument 5 is copied into the parameter variable num.
Trang 252 Passing Arguments to a
Method
Trang 26Argument and Parameter Data
Type Compatibility
sure that the argument's data type is compatible with the parameter variable's data type
conversation if the argument's data type is ranked lower than the parameter variable's data type
short s = 1;
displayValue(s); // converts short to int
Trang 27Argument and Parameter Data
Type Compatibility
byte b = 2;
displayValue(b); // converts byte to int
to a lower-ranking data type
double d = 1.0;
displayValue(d); // Error! Can't convert
// double to int.
Trang 28Parameter Variable Scope
which the parameter is declared
parameter variable by its name
public static void displayValue(int num)
Trang 29Passing Multiple Arguments
variables
public static void showSum(double num1, double num2) {
sum = num1 + num2;
System.out.println(“The sum is ” + sum);
Trang 30sum = num1 + num2;
System.out.println(“The sum is ” + sum);
Trang 31Passing Multiple Arguments
have data type listed before its name
public static void showSum(double num1, num2) // Error!
public static void showSum(double num1, double num2)
Trang 32Arguments Are Passed by Value
are passed by value
parameter variable
distinct from the arguments
method, it has no affect on the original argument
Trang 33Arguments Are Passed by Value
Trang 34Arguments Are Passed by Value
Trang 35Arguments Are Passed by Value
changed in the changeMe method, the argument number is not mofified
the number variable
Trang 36Passing String Object References to a Method
String objects as arguments
public static void showLength(String str) {
Trang 37into the str parameter variable.
both name and str reference the same object
Trang 39Passing String Object References to a Method
The name variable holds
the address of a String object.
The str parameter variable holds
the address of the same
Trang 40Passing String Object References to a Method
method can change the contents of any String
object that has been passed to it as an argument
which means that they can not be changed
Trang 41Passing String Object
References to a Method
Trang 42Passing String Object
References to a Method
Trang 43The str parameter variable holds
the address of the same
Trang 44The str parameter variable holds
the address of a different
“Dickens”
A String object
Trang 45Using the @param Tag in Documentation Comments
method, you can provide a description of each
parameter by using a @param tag
sum = num1 + num2;
System.out.println(“The sum is ” + sum);
}
Trang 473 More about Local Variables
in which they are declared
method's local variables
method, other method may have own local
variables with the same name
Trang 48More about Local Variables
Trang 49More about Local Variables
Trang 50More about Local Variables
the program can only see one of them at a time
because they are in different methods
variable declared inside texas is visible
birds variable declared inside california is
visible
Trang 51Local Variable Lifetime
method is executing This is known as the lifetime
of a local variable
its parameter variables are created in memory,
and when the method ends, the local variables
and parameter variables are destroyed
Trang 52Initializing Local Variables with
Parameter Values
initialize a local variable
public static void showSum(double num1, double num2) {
double sum; // To hold the sum
sum = num1 + num2;
System.out.println(“The sum is ” + sum);
}
We can combine these Statements into one.
Trang 53Initializing Local Variables with
Parameter Values
entire method in which it is declared, we can use parameter variables to initialize local variables
public static void showSum(double num1, double num2) {
double sum = num1 + num2;
System.out.println(“The sum is ” + sum);
}
Trang 54Warning !
with a default value They must be given value
before they can be used
been given a value, a compiler error will result
Trang 55variable x has not been given a value.
Trang 56to the statement that called it.
known as value-returning methods.
int num;
num = Integer.parseInt(“700”);
Trang 57Defining a Value-Returning
Method
we must decide what type of value the method will return
in the method header
a value, uses the key word void as its return type
in the method header
Trang 58Defining a Value-Returning
Method
double, boolean, … or other valid data type in its header
public static int sum(int num1, int num2)
Trang 59return Statement
value-returning method
returns value to the statement that called the
Trang 60return Statement
variable, literal, or mathematical expression
public static int sum(int num1, int num2) {
return num1 + num2;
}
the same data type as the return type specified in the method header, or compatible with it
return expression, if necessary
Trang 61Calling a Value-Returning Method
Trang 62Calling a Value-Returning Method
Trang 63Calling a Value-Returning Method
total = sum(value1, value2);
public static int sum(int num1, int num2) {
Trang 65Using the @return Tag in Documentation Comments
the return value when writing the documentation comments
@return Description
description of the method
the end of the documentation comment (*/
symbol), or at the beginning of another tag
Trang 66Returning a boolean Value
public static boolean isValid(int number) {
Trang 67System.out.println(“The value is out
of range.”);
Trang 68Retuning a Reference to a String
Object
reference to a non-primitive type, such as a
String object
Trang 69Retuning a Reference to a String
Object
Trang 70Retuning a Reference to a String
Object
customerName = fullName("John", "Martin");
public static String fullName(String first, String last) {
A String object
Trang 72Problem Solving with Method
at a time by methods
smaller pieces is called functional decomposition.
one long method, small methods are written
These small methods can then be executed in the desired order to solve the problem
Trang 73Problem Solving with Methods
sales amounts from a file, and then display the the total sales and average daily sales
Trang 74Problem Solving with Methods
Trang 75Problem Solving with Methods
Trang 76Problem Solving with Methods
Trang 77Problem Solving with Methods
Trang 78Exercises
Trang 79Exercises