Methods: Starting Out With Java: From Control Structures Through Objects Fifth Edition
Methods: Starting Out With Java: From Control Structures Through Objects Fifth Edition
Methods
Starting Out with Java:
From Control Structures through Objects
Fifth Edition
by Tony Gaddis
Chapter Topics
Introduction to Methods
Passing Arguments to a Method
More About Local Variables
Returning a Value from a Method
Problem Solving with Methods
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-2
5-3
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-4
5-5
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-6
Return
Type
Method
Name
Parentheses
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-7
staticmethod
class
5-8
Calling a Method
A method executes when it is called.
The main method is automatically called when a
program starts, but other methods are executed by
method call statements.
displayMessage();
5-9
Documenting Methods
A method should always be documented by
writing comments that appear just before the
methods definition.
The comments should provide a brief
explanation of the methods purpose.
The documentation comments begin with /**
and end with */.
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-10
5-11
{
System.out.println("The value is " + num);
}
The method will display
The value is 5
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-12
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-13
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-14
5-15
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-16
showLength(name);
Warren
address
The address of the object is
copied into the str parameter.
address
5-17
address
Warren
address
Joe
5-18
5-19
5-20
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-21
40
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-22
Returning a booleanValue
Sometimes we need to write methods to test
arguments for validity and return true or false
public static boolean isValid(int number)
{
boolean status;
if(number >= 1 && number <= 100)
status = true;
else
status = false;
return status;
}
Calling code:
int value = 20;
if(isValid(value))
System.out.println("The value is within range");
else
System.out.println("The value is out of range");
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-23
John Martin
See example:
ReturnString.java
2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
5-24
5-25
5-26