Download presentation
Presentation is loading. Please wait.
Published byRandolph Rudolf Garrison Modified over 8 years ago
1
Chapter 5 Methods
2
2 Contents 1. Introduction to Methods 2. Passing Arguments to a Method 3. More about Local Variables 4. Returning a Value from a Method 5. Problem Solving with Methods
3
3 1. Introduction to Methods A method is a collection of statements that performs a specific task. We have experienced methods in two ways: Creating a method named main in every program Using predefined methods from the Java API, such as System.out.println Integer.parseInt Math.pow
4
4 1. Introduction to Methods Methods are commonly used to break a problem into small manageable pieces. Instead of writing one long method that contains all of the statements, several small methods that each solve a specific part of the problem can be written. This approach is called divide and conquer because a large problem is divided into several problems.
5
5 1. Introduction to Methods public class BigProblem { public static void main(String[] args) { statement; } public class DividedProblem { public static void main(String[] args) { statement; } public static void method2() { statement; } public static void method3() { statement; } public static void method4() { statement; }
6
6 1. Introduction to Methods Another reason to write methods is that they simplify programs. If a specific task is performed in several places in a program, a method can be written once and then be executed anytime it is needed. This benefit of using methods is known as code reuse.
7
7 void Methods and Value- Returning Methods Two general categories of methods: void methods Value-returning methods A void method performs a task and then terminates. int number = 7; System.out.println(number); number = 0; This method displays the value on the screen, and then terminates.
8
8 void Methods and Value- Returning Methods A value-returning methods not only performs a task, but also sends a value back to the code that called it. int number; String str = “700”; number = Integer.parseInt(str); This method converts the string to a number, and then returns the number to this line of code.
9
9 Defining a void Method To create a method we must write its definition, which consists of two general parts: A header Appears at the beginning of a method definition Lists several important things about the method Method Modifiers Return type Method's name Arguments A body A collection of statements that are performed when the method is executed. public static void main(String[] args) { System.out.println(“Hello World!”); } Header Body
10
10 Defining 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.
11
11 Calling a Method A method executes when it is called. The main method is automatically called when a program starts. Other methods are executed by method call statements. When a method is called, the JVM branches to 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.
12
12 Calling a Method
13
13 Branching in the SimpleMethod.java Program 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."); }
14
14 Calling a Method
15
15 Calling a Method Problem: Write a program to ask the user to enter 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: 1 (very bad) through 10 (excellent) 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.
16
16 Calling a Method
17
17 Calling a Method
18
18 Checkpoint 5.1 5.2 5.3 5.4 5.5
19
19 Hierarchical Method Calls Methods can also called in a hierarchical, or layered fashion. Method A can call method B, which can call method C. When method C finishes, the JVM returns to method B. When method B finishes, the JVM returns to method A.
20
20 Hierarchical Method Calls
21
21 Using Documentation Comments with Methods You should always document a method by writing comments that appear just before the method's definition. The comment should provide a brief explanation of the method's purpose. Recall that documentation comments begin with /** and end with */. These types of comments can be read and processed by a program named javadoc which produces attractive HTML documentation.
22
22 2. Passing Arguments to a Method Values that are sent into a method are called arguments. System.out.println(“Hello World!”); This call statement passes “Hello World!” as an argument. number = Integer.parseInt(str); This call statement passes the contents of the str variable as an argument.
23
23 2. Passing Arguments to a Method A parameter variable, sometimes simply referred 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); } int num declaration of an parameter variable enables the displayValue method to accept an integer value as an argument.
24
24 2. Passing Arguments to a Method public static void displayValue(int num) { System.out.println(“The value is “ + num); } A call to the displayValue displayValue(5); This statement executes the displayValue method. Statements call the displayValue method with various arguments passed: displayValue(x); displayValue(x * 4); The argument 5 is copied into the parameter variable num.
25
25 2. Passing Arguments to a Method
26
26 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 a widening 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
27
27 Argument and Parameter Data Type Compatibility byte b = 2; displayValue(b);// converts byte to int Java will not automatically convert an argument to a lower-ranking data type. double d = 1.0; displayValue(d);// Error! Can't convert // double to int.
28
28 Parameter Variable Scope A parameter variable's scope is the method in which the parameter is declared. No statement outside the method can access the parameter variable by its name. public static void displayValue(int num) { System.out.println(“The value is “ + num); } The scope of num is the method displayValue.
29
29 Passing Multiple Arguments The method showSum has two parameter variables 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 method showSum accepts two arguments showSum(5.1, 10.2); Parameter list Argument list
30
30 Passing Multiple Arguments showSum(5.1, 10.2); 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 arguments are passed into the parameters variables in the order that they appear in the method call. The argument 5.1 is copied to the num1 parameter. The argument 10.2 is copied to the num2 parameter.
31
31 Passing Multiple Arguments Each parameter variable in a parameter list must have data type listed before its name. public static void showSum(double num1, num2) // Error! public static void showSum(double num1, double num2)
32
32 Arguments Are Passed by Value In Java, all arguments of the primitive data types are passed by value Only copy of an argument's value is passed into a parameter variable. A method's parameter variables are separate and distinct from the arguments. If a parameter variable is changed inside a method, it has no affect on the original argument.
33
33 Arguments Are Passed by Value
34
34 Arguments Are Passed by Value
35
35 Arguments Are Passed by Value Even though the parameter variable myValue is changed in the changeMe method, the argument number is not mofified. The myValue variable contains only a copy of the number variable.
36
36 Passing String Object References to a Method You can write methods that accept references to String objects as arguments. public static void showLength(String str) { System.out.println(str + “ is ” + str.length() + “ characters long.”); } String name = “Smith”; showLength(name); Smith is 5 characters long.
37
37 Passing String Object References to a Method Recall that a reference variable holds the address of an object. The address that is stored in the name is passed into the str parameter variable. When the showLength method is executing, both name and str reference the same object.
38
38 Passing String Object References to a Method String name = “Smith”; showLength(name); public static void showLength(String str) { System.out.println(str + “ is ” + str.length() + “ characters long.”); } address “Smith” A String object
39
39 Passing String Object References to a Method Both name and str reference the same object The name variable holds the address of a String object. The str parameter variable holds the address of the same String object. address “Smith” A String object
40
40 Passing String Object References to a Method This might lead you to the conclusion that a method can change the contents of any String object that has been passed to it as an argument. However, String objects in Java are immutable, which means that they can not be changed.
41
41 Passing String Object References to a Method
42
42 Passing String Object References to a Method
43
43 Passing String Object References to a Method Before executing the statement str = “Dickens” The name variable holds the address of a String object. The str parameter variable holds the address of the same String object. address “Shakespeare ” A String object
44
44 Passing String Object References to a Method After executing the statement str = “Dickens” The name variable holds the address of a String object. The str parameter variable holds the address of a different String object. address “Shakespeare ” A String object “Dickens” A String object
45
45 Using the @param Tag in Documentation Comments When writing the documentation comments for a method, you can provide a description of each parameter by using a @param tag. /** 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;// To hold the sum sum = num1 + num2; System.out.println(“The sum is ” + sum); }
46
46 Checkpoint 5.6 5.7 5.8 5.9 5.10
47
47 3. More about Local Variables A local variable is declared inside a method. It is called local because it is local to the method in which they are declared. Statements outside a method cannot access that method's local variables. A method's local variable is hidden from other method, other method may have own local variables with the same name.
48
48 More about Local Variables
49
49 More about Local Variables
50
50 More about Local Variables Although there are two variables named birds, the program can only see one of them at a time because they are in different methods. When the texas method is executing, the birds variable declared inside texas is visible. When the california method is executing, the birds variable declared inside california is visible.
51
51 Local Variable Lifetime A method's local variables exist only while the method is executing. This is known as the lifetime of a local variable. When the method begins, its local variables and its parameter variables are created in memory, and when the method ends, the local variables and parameter variables are destroyed.
52
52 Initializing Local Variables with Parameter Values It is possible to use a parameter variable to 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.
53
53 Initializing Local Variables with Parameter Values Because the scope of a parameter variable is the 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); }
54
54 Warning ! Local variables are not automatically initialized with a default value. They must be given value before they can be used. If we attempt to use a local variable before it has been given a value, a compiler error will result.
55
55 Warning ! public static void myMethod() { int x; System.out.println(x); // Error! // x has no value. } This code will cause a compiler error because the variable x has not been given a value.
56
56 4. Returning a Value from a Method Data may be passed into a method by way of parameter variables. Data may also be returned from a method, back to the statement that called it. Methods that return a value are appropriately known as value-returning methods. int num; num = Integer.parseInt(“700”);
57
57 Defining a Value-Returning Method When we are writing a value-returning method, we must decide what type of value the method will return. We must specify the data type of the return value in the method header. Recall that a void method, which does not return a value, uses the key word void as its return type in the method header.
58
58 Defining a Value-Returning Method A value-returning method will use int, double, boolean, … or other valid data type in its header. public static int sum(int num1, int num2) { int result; result = num1 + num2; return result; }
59
59 return Statement We must have a return statement in a value- returning method. It causes the method to end execution and it returns value to the statement that called the method. The general format of the return statement is as follows: return Expression; Expression is the value to be returned.
60
60 return Statement It is any expression that has a value, such as a variable, literal, or mathematical expression. public static int sum(int num1, int num2) { return num1 + num2; } The return statement's expression must be of the same data type as the return type specified in the method header, or compatible with it. Java will automatically widen the value of the return expression, if necessary.
61
61 Calling a Value-Returning Method
62
62 Calling a Value-Returning Method
63
63 Calling a Value-Returning Method Arguments passed to sum and a value returned total = sum(value1, value2); public static int sum(int num1, int num2) { int result; result = num1 + num2; return result; } 20 40 60
64
64 Calling a Value-Returning Method int x = 10, y = 15; double average; average = sum(x, y) / 2.0; int x = 10, y = 15; System.out.println(“The sum is “ + sum(x, y));
65
65 Using the @return Tag in Documentation Comments Using a @return tag to provide a description of the return value when writing the documentation comments. The general format of a @return tag comment @return Description Description is a description of the return value. The @return tag must appear after the general description of the method. The description can span several lines. It ends at the end of the documentation comment ( */ symbol), or at the beginning of another tag.
66
66 Returning a boolean Value public static boolean isValid(int number) { boolean status; if(number >= 1 && number <= 100) status = true; else status = false; return status; }
67
67 Returning a boolean Value int value = 20; if(isValid(value)) System.out.println(“The value is within range.”); else System.out.println(“The value is out of range.”);
68
68 Retuning a Reference to a String Object A value-returning method can also return a reference to a non-primitive type, such as a String object.
69
69 Retuning a Reference to a String Object
70
70 Retuning 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” A String object
71
71 Checkpoint 5.11 5.12 5.13 5.14
72
72 Problem Solving with Method A large, complex problem can be solved a piece at a time by methods. The process of breaking down a problem into smaller pieces is called functional decomposition. In functional decomposition, instead of writing one long method, small methods are written. These small methods can then be executed in the desired order to solve the problem.
73
73 Problem Solving with Methods Problem: Write a program to read 30 days of sales amounts from a file, and then display the the total sales and average daily sales. Ask the user to enter the name of the file. Get the total of the sales amounts in the file. Calculate the average daily sales. Display the total and average daily sales.
74
74 Problem Solving with Methods
75
75 Problem Solving with Methods
76
76 Problem Solving with Methods
77
77 Problem Solving with Methods
78
78 Exercises 4. Paint job Estimator (page 276): The program should have methods such as The number of gallons of paint required The hours of labor required The cost of the paint The labor charges The total cost of the paint job
79
79 Exercises 8. Conversion Program (page 277) 13. isPrime Method (page 279)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.