chapter 5: methods - tom reboldtomrebold.com/csis10as13/lectures/05/lec5.pdf · by tony gaddis...
TRANSCRIPT
© 2010 Pearson Addison-Wesley. All rights reserved.
Addison Wesley
is an imprint of
Starting Out with Java:
From Control Structures through Objects
Fourth Edition
by Tony Gaddis
Chapter 5: Methods
Reading Quiz
1. In Java a named block of code that accomplishes a specific task is called a: a) Function
b) Subroutine
c) Loop
d) Method
2. A _______ method is one that does not return a value when finished. a) boolean
b) String
c) void
d) class
5-3
Chapter Topics
Chapter 5 discusses the following main topics:
– Introduction to Methods
– Passing Arguments to a Method
– More About Local Variables
– Returning a Value from a Method
– Problem Solving with Methods
What is a Method?
A named group of Java commands.
Using Methods to Build A Shakespearean Insult Generator
Insult me!
How it works
PseudoCode for Insult Generator
1. Clear the screen
2. Display “Shakespearean Insult Generator”
3. Begin the insult with Thou
4. Add adjectives
5. Add noun
6. Add insult ending
clearScreen()
Method call
Method header
Method body
Method declaration
5-8
The Method Call
public static void main(String[] args)
{
clearScreen();
}
Call
5-9
Two Parts of Method Declaration
public static void clearScreen()
{
System.out.println(“\f");
}
Header
Body
public class Checkpoint
{
public static void main(String[] args)
{
method1();
method1();
method2();
}
public static void method1()
{
System.out.println("abra");
}
public static void method2()
{
System.out.print("cad");
method1();
}
}
What is the output of this program?
What is the output?
Circle method headers.
Box method calls
public class Checkpoint
{
public static void main(String[] args)
{
method1();
method1();
method2();
}
public static void method1()
{
System.out.println("abra");
}
public static void method2()
{
System.out.print("cad");
method1();
}
}
What is the output of this program?
circle method headers
box method calls
output:
abra
abra
cadabra
beginInsult()
adjective() - use if-else-if
loop in main() for many insults
2 adjectives
noun() - use switch
endInsult()
Let’s write some methods
5-13
Why Write Methods?
• Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer.
• Methods simplify programs. If a specific task is performed in several places in the program, a method can be written once to perform that task, and then be executed anytime it is needed. This is known as code reuse.
generateInsults()
generateInsults(500) Arguments and parameters
Data types must match
Can pass many arguments like Math.pow()
Pass by reference; scope
Better and Deeper
Checkpoint
Checkpoint
• argument is given to method call
• parameter receives argument in method body
99 1.5
99 1.5
0 0
99 1.5
Ask user for # of insults.
getNumInsults()
Returns an int
User Input and Passing Data
Methods we know already. Do they receive and/or return data?
int i = keyboard.nextInt();
System.out.println(“Hello World”);
String upper = name.toUpperCase();
clearScreen();
System.out.println( Math.sqrt(49) );
5-21
Defining a Value-Returning Method
public static int sum(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
Return type
This expression must be of the
same data type as the return type
The return statement
causes the method to end
execution and it returns a
value back to the
statement that called the
method.
5-22
Calling a Value-Returning Method
total = sum(value1, value2);
public static int sum(int num1, int num2)
{
int result;
result = num1 + num2;
return result;
}
20 40
60
is it void or value-returning?
Checkpoint
5.3b Is the following line of code a method header or method call? void or
value-returning?
is it void or value-returning?
Checkpoint
a void method has no return value
when invoked it appears on a line by itself
a value returning method comes back with a value when complete
must appear in an assignment statement or output line.
5.3b Is the following line of code a method header or method call? void or
value-returning?
• Any: int, double, boolean, String, …
• Any primitive or object
• Parameter type must match Argument type.
• Return type must match the use in the call.
What data types can be passed or returned?
5-26
Returning a Reference to a String Object
customerName = fullName("John", "Martin");
public static String fullName(String first, String last)
{
String name;
name = first + " " + last;
return name;
}
See example:
ReturnString.java
address
“John Martin”
Local variable name holds
the reference to the object.
The return statement sends
a copy of the reference
back to the call statement
and it is stored in customerName.
public class ReturnString
{
public static void main(String[] args)
{
String customerName;
customerName = fullName("John", "Martin");
System.out.println(customerName);
}
public static String fullName(String first, String last)
{
String name;
name = first + " " + last;
return name;
}
}
String Returning Method Example
Checkpoint
Checkpoint
public static int days( int years, int months, int
weeks)
public static double distance(double rate, double time)