45
Methods Chapter 5

Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

Embed Size (px)

Citation preview

Page 1: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

MethodsChapter 5

Page 2: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-2

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.

Page 3: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-3

void Methods and Value-Returning Methods

A void method is one that simply performs a task and then terminates.

System.out.println("Hi!");A value-returning method not only

performs a task, but also sends a value back to the code that called it.

int number = Integer.parseInt("700.0");

Page 4: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-4

Defining a void MethodTo create a method, you must

write a definition, which consists of a header and a body.

The method header, which appears at the beginning of a method definition, lists several important things about the method, including the method’s name.

The method body is a collection of statements that are performed when the method is executed.

Page 5: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-5

Two Parts of Method Declaration

public static void displayMesssage()

{

System.out.println("Hello");

}

Header

Body

Page 6: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-6

Parts of a Method Header

public static void displayMessage (){ System.out.println("Hello");

}

Method Modifiers

Return Type

Method Name Parentheses

Page 7: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-7

Parts of a Method HeaderMethod modifiers

◦ public—method is publicly available to code outside the class

◦ static—method belongs to a class, not a specific object.

Return type—void or the data type from a value-returning method

Method name—name that is descriptive of what the method does

Parentheses—contain nothing or a list of one or more variable declarations if the method is capable of receiving arguments.

Page 8: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

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();Notice that the method modifiers and

the void return type are not written in the method call statement. Those are only written in the method header.

Page 9: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-9

public class SimpleMethod{

public static void main(String[] args){

System.out.println(“Hello from the main method!”);

displayMessage();System.out.println(“Back in the main method.”);

}

public static void displayMessage(){

System.out.println(“Hello from the displayMessage method!”);

}

}

Calling a Method

Page 10: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-10

public class DeepAndDeeper{

public static void main(String[] args){

System.out.println(“I am starting in main.”);deep();System.out.println(“Now I am back in the main

method.”);}

public static void deep(){

System.out.println(“I am now in deep.”); deeper();System.out.println(“Now I am back in deep.”);

}

public static void deeper(){

System.out.println(“I am now in deeper.”); }

}

Hierarchical Method Calls

12

2

34

4

5

6

7

Page 11: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-11

Documenting MethodsA method should always be

documented by writing comments that appear just before the method’s definition.

The comments should provide a brief explanation of the method’s purpose.

The documentation comments begin with /** and end with */.

Page 12: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-12

Documenting Methodspublic class SimpleMethod{

public static void main(String[] args){

System.out.println(“Hello from the main method!”);

displayMessage();System.out.println(“Back in the main method.”);

}

/**The displayMessage method displays a greeting

*/public static void displayMessage(){

System.out.println(“Hello from the displayMessage method!”);

}

}

Page 13: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-13

Passing Arguments to a Method

Values that are sent into a method are called arguments.System.out.println("Hello");

number = Integer.parseInt(str);

The data type of an argument in a method call must correspond to the variable declaration in the parentheses of the method declaration. The parameter is the variable that holds the value being passed into a method.

By using parameter variables in your method declarations, you can design your own methods that accept data this way.

Page 14: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-14

Passing Arguments to a Method

public class PassArg{

public static void main(String[] args){

int x = 10;

displayValue(x);displayValue(x * 4);

}

public static void displayValue(int num){

System.out.println(“The value is: ” + num); }

}

Page 15: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-15

Passing 5 to the displayValue Method

displayValue(5);

public static void displayValue(int num){System.out.println("The value is " + num);

}

The argument 5 is copied into the parameter variable num.

The method will display: The value is 5

Page 16: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-16

Argument and Parameter Data Type Compatibility

When you pass an argument to a method, be sure that the argument’s data type is compatible with the parameter variable’s data type.

Java will automatically perform widening conversions, but narrowing conversions will cause a compiler error.double d = 1.0;

displayValue(d);

Error! Can’t convert double to int

Page 17: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-17

Passing Multiple Arguments

showSum(5, 10);

public static void showSum(double num1, double num2)

{

double sum; //to hold the sum

sum = num1 + num2;

System.out.println("The sum is " + sum);

}

The argument 5 is copied into the num1 parameter.

The argument 10 is copied into the num2 parameter.

NOTE: Order matters!

Page 18: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-18

Arguments are Passed by Value

In Java, all arguments of the primitive data types are passed by value, which means that only a copy of an argument’s value is passed into a parameter variable.

A method’s parameter variables are separate and distinct from the arguments that are listed inside the parentheses of a method call.

If a parameter variable is changed inside a method, it has no affect on the original argument.

Page 19: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-19

public class PassArg{

public static void main(String[] args){

int number = 99;

System.out.println(“Number is “ + number);

changeMe(number);

System.out.println(“Number is “ + number);}

public static void changeMe(int myValue){

System.out.println(“I am changing the value.”);

myValue = 0;

System.out.println(“Now the value is “ + myValue);}

}

Only a copy of an argument’s value is passed into a parameter variable

Program outputNumber is 99I am changing the valueNow the value is 0Number is 99

Page 20: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-20

Passing Object References to a Method

Recall that a class type variable does not hold the actual data item that is associated with it, but holds the memory address of the object. A variable associated with an object is called a reference variable.

When an object such as a String is passed as an argument, it is actually a reference to the object that is passed.

Page 21: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-21

Passing a Reference as an Argument

showLength(name);

public static void showLength(String str){System.out.println(str + " is " + str.length() + " characters long.");str = "Joe”

}

address

“Warren”

Both variables reference the same object

The address of the object is copied into the str parameter.

Page 22: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-22

Strings are Immutable Objects

Strings are immutable objects, which means that they cannot be changed. When the line

str = "Joe";

is executed, it cannot change an immutable object, so creates a new object.

address

address

“Warren”

“Joe”

The name variable holds the address of a String objectThe str variable holds the address of a different String object

Page 23: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-23

public class PassString{

public static void main(String[] args){

String name = “Shakespeare”;

System.out.println(“In main, the name is “ + name);

changeName(name);

System.out.println(“Back in main the name is “ + name);}

public static void changeName(String str){

str = “Dickens”;

System.out.println(“In changeName, the name is now “ + str);}

}

Program outputIn main, the name is ShakespeareIn changeName, the name is now DickensBack in main the name is Shakespeare

Page 24: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-24

@param Tag in Documentation Comments

You can provide a description of each parameter in your documentation comments by using the @param tag.

General format@param parameterName Description

All @param tags in a method’s documentation comment must appear after the general description.The description can span several lines.

Page 25: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-25

/**The showSum method displays the sum

of two numbers.@param num1 The first number.@param num2 The second number.

*/

public static void showSum(double num1, double num2)

{double sum;sum = num1 + num2;System.out.println(“The sum is “ +

sum);}

Page 26: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-26

More About Local Variables

A local variable is declared inside a method and is not accessible to statements outside the method.

Different methods can have local variables with the same names because the methods cannot see each other’s local variables.

A method’s local variables exist only while the method is executing. When the method ends, the local variables and parameter variables are destroyed and any values stored are lost.

Local variables are not automatically initialized with a default value and must be given a value before they can be used.

Page 27: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-27

public class LocalVars{

public static void main(String[] args){

texas();california();

}

public static void texas(){

int birds = 5000;

System.out.println(“In texas there are “ + birds + “ birds”);}

public static void california(){

int birds = 3500;

System.out.println(“In california there are “ + birds + “ birds”);}

}

Program outputIn texas there are 5000 birdsIn california there are 3500 birds

Page 28: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-28

Returning a Value from a Method

Data can be passed into a method by way of the parameter variables. Data may also be returned from a method, back to the statement that called it.

int num = Integer.parseInt("700");

The string “700” is passed into the parseInt method.

The int value 700 is returned from the method and assigned to the num variable.

Page 29: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-29

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.

Page 30: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-30

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

Page 31: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-31

@return Tag in Documentation Comments

You can provide a description of the return value in your documentation comments by using the @return tag.

General format@return Description

The @return tag in a method’s documentation comment must appear after the general description. The description can span several lines.

Page 32: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-32

public class ValueReturn{

public static void main(String[] args){

int total, value1 = 20, value2 = 40;

total = sum(value1, value2);System.out.println(“The sum of “ + value1 + “ and “ + value2 + “ is

“ + total);}

/**The sum method returns the sum of its two parameters.@param num1 The first number to be added.@param num2 The second number to be added.@return The sum of num1 and num2

*/

public static int sum(int num1, int num2){

int result;

result = num1 + num2;

return result;}

}

Program outputThe sum of 20 and 40

is 60

Page 33: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-33

Returning a booleanValue

Sometimes we need to write methods to test arguments for validity and return true or false

Page 34: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-34

public static void main(String[] args){

int value = 20;

if(isValid(value))System.out.println("The value is within range");

elseSystem.out.println("The value is out of range");

}

public static boolean isValid(int number){ boolean status;

if(number >= 1 && number <= 100) status = true; else status = false;

return status;}

Page 35: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-35

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;

}

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.

Page 36: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-36

public class ReturnString{

public static void main(String[] args){

String customerName;

customerName = fullName(“John”, “Martin”);System.out.println(customerName);

}

/**The fullName method accepts two String arguments containing a first

and last name.It concatenates them into a single String object.@param first The first name.@param last The last name.@return A reference to a String object containing the first and last

names.*/

public static String fullName(String first, String last){

String name;

name = first + “ “ + last;

return name;}

}

Page 37: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-37

Problem Solving with MethodsA large, complex problem can be

solved a piece at a time by methods.

The process of breaking a problem down into smaller pieces is called functional decomposition.

If a method calls another method that has a throws clause in its header, then the calling method should have the same throws clause.

Page 38: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-38

import java.util.Scanner;import java.io.*;import java.text.DecimalFormat;import javax.swing.JOptionPane;

/** This program opens a file containing the sales amounts for 30 days. It

calculates and displaysthe total sales and average daily sales.

*/

public class SalesReport{

public static void main(String[] args){

final int NUM_DAYS = 30; // Number of days of salesString filename; // The name of the file to opendouble totalSales; // Total sales for perioddouble averageSales; // Average daily sales

filename = getFileName(); // Get the name of the filetotalSales = getTotalSales(filename); // Get the total sales

from the file

averageSales = totalSales / NUM_DAYS; // Calculate the averagedisplayResults(totalSales, averageSales); // Display the total and

average

System.exit();}

Page 39: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-39

/** The getFileName method prompts the user to enter the name of the file to

open@return A reference to a String object containing the name of the file

*/

public static String getFileName(){

String file; // To hold the file name

file = JOptionPane.showInputDialog(“Please enter file name for sales amounts: “);

return file; // Return the file name}

Page 40: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-40

import java.util.Scanner;import java.io.*;import java.text.DecimalFormat;import javax.swing.JOptionPane;

/** This program opens a file containing the sales amounts for 30 days. It

calculates and displaysthe total sales and average daily sales.

*/

public class SalesReport{

public static void main(String[] args){

final int NUM_DAYS = 30; // Number of days of salesString filename; // The name of the file to opendouble totalSales; // Total sales for perioddouble averageSales; // Average daily sales

filename = getFileName(); // Get the name of the filetotalSales = getTotalSales(filename); // Get the total sales

from the file

averageSales = totalSales / NUM_DAYS; // Calculate the averagedisplayResults(totalSales, averageSales); // Display the total and

average

System.exit();}

Page 41: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-41

/** The getTotalSales method opens a file and reads the daily sales amounts,

accumulating thetotal. The total is returned.@param filename The name of the file to open@return The total of the sales amounts

*/

public static double getTotalSales(String filename) throws IOException{

double total = 0.0; // Accumulatordouble sales; // A daily sales amount

File file = new File(filename);Scanner inputFile = new Scanner(file); // Open the file

while (inputFile.hasNext()) // Repeats until end of file{

sales = inputFile.nextDouble(); // Read a double from the file

total +=sales; // Add sales to total}

inputFile.close(); // Close inputFile

return total;}

Page 42: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-42

import java.util.Scanner;import java.io.*;import java.text.DecimalFormat;import javax.swing.JOptionPane;

/** This program opens a file containing the sales amounts for 30 days. It

calculates and displaysthe total sales and average daily sales.

*/

public class SalesReport{

public static void main(String[] args) throws IOException{

final int NUM_DAYS = 30; // Number of days of salesString filename; // The name of the file to opendouble totalSales; // Total sales for perioddouble averageSales; // Average daily sales

filename = getFileName(); // Get the name of the filetotalSales = getTotalSales(filename); // Get the total sales

from the file

averageSales = totalSales / NUM_DAYS; // Calculate the averagedisplayResults(totalSales, averageSales); // Display the total and

average

System.exit();}

Page 43: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-43

/** The displayResults method displays the total and average daily sales@param total The total sales.@param avg The average daily sales.

*/

public static void displayResults(double total, double avg){

// Create a DecimalFormat object capable to format a dollar amountDecimalFormat dollar = new DecimalFormat(“#,###.00”);

// Display the total and average salesJOptionPane.showMessageDialog(null, “The total sales for the period

is $” +dollar.format(total) + “\nThe average daily sales

were $” +dollar.format(avg));

}}

Page 44: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-44

import java.util.Scanner;import java.io.*;import java.text.DecimalFormat;import javax.swing.JOptionPane;

/** This program opens a file containing the sales amounts for 30 days. It

calculates and displaysthe total sales and average daily sales.

*/

public class SalesReport{

public static void main(String[] args){

final int NUM_DAYS = 30; // Number of days of salesString filename; // The name of the file to opendouble totalSales; // Total sales for perioddouble averageSales; // Average daily sales

filename = getFileName(); // Get the name of the filetotalSales = getTotalSales(filename); // Get the total sales

from the file

averageSales = totalSales / NUM_DAYS; // Calculate the averagedisplayResults(totalSales, averageSales); // Display the total and

average

System.exit();}

Page 45: Methods Chapter 5. 5-2 Why Write Methods? Methods are commonly used to break a problem down into small manageable pieces. This is called divide and conquer

5-45

Calling Methods that Throw Exceptions

Note that the main and getTotalSales methods in SalesReport.java have a throws IOException clause.

All methods that use a Scanner object to open a file must throw or handle IOException.

You will learn how to handle exceptions in Chapter 12.

For now, understand that Java requires any method that interacts with an external entity, such as the file system to either throw an exception to be handled elsewhere in your application or to handle the exception locally.