Presentation is loading. Please wait.

Presentation is loading. Please wait.

11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.

Similar presentations


Presentation on theme: "11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms."— Presentation transcript:

1 11 Chapter 5 METHODS

2 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms function or procedure instead of method for this construct. Regardless of what they are called, methods allow you to create self-contained units that perform the tasks necessary in a program. The capability to divide the functionality of a program into a number of separate methods makes it easier to develop, test, and maintain programs.

3 33 void METHODS AND VALUE-RETURNING METHODS There are two general categories of methods: void methods and value-returning methods. –A method that performs a task, but does not return a value is called a void method. –A value-returning method not only performs a task, but also sends a value back to the code that called it.

4 44 void METHODS AND VALUE-RETURNING METHODS The println method of the System.out object is an example of a void method. It performs its job, displaying a string of characters in a console window, and then terminates. The segment below calls the void method println to display a string of characters in a console window. int number = 10; System.out.println("The number is: " + number);

5 55 void METHODS AND VALUE-RETURNING METHODS The parseInt method of the Integer class is an example of a value-returning method. It does its job of converting the string it receives as its argument to an int and then returns this value back to the code that called it. For example, the segment below calls the parseInt method to convert a string to an integer, assigns the integer returned by the method to the variable number, and then increases the contents of number by 5. String numberString = "15"; int number; number = Integer.parseInt(numberString); number += 5;

6 66 DEFINING A METHOD Every Java application program must include the definition of a method named main. Java programs can contain multiple methods.

7 77 DEFINING A METHOD To create a method you write a method definition. A method definition includes the method header and the method body. –The method header, which is the beginning of the method definition, gives important information about the method, including its name. –The body is the group of statements, enclosed in braces, which perform the methods operation.

8 88 DEFINING A METHOD Here is an example of the definition of a simple method called displayGrade. public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; } This is the header of the method named displayGrade. The body of the method consists of the statement(s) that perform the operation of the method.

9 99 DEFINING A METHOD The key words public and static are method modifiers. Every method we write in this class will begin with these modifiers. public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; }

10 10 DEFINING A METHOD The return type of the method immediately precedes the name of the method in the method header. The return type is the data type of the value returned by the method. Here the return type is void. This means the method is a void method (it does not return a value). public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; } This is the return type.

11 11 DEFINING A METHOD The name of the method is displayGrade. The name of a method is another type of identifier, so the rules discussed previously for naming variables also apply to method names. public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; }

12 12 DEFINING A METHOD The method name is followed by a parenthesized parameter list. The parameter list is a list of variables that hold the values passed into the method. A parameter, of type char, named grade, is declared in the method displayGrade. This allows the method to accept a value of type char as an argument. public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; } The method displayGrade receives a single argument that is copied into the parameter variable grade when the method is called.

13 13 DEFINING A METHOD Notice that there is no semicolon following the method header. public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; } Do not put a semicolon here. The complete method definition includes the body of the method.

14 14 DEFINING A METHOD Even if the body of the method consists of a single statement, the statement must be enclosed in braces. public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; } The braces are required around the statement(s) in the body of a method.

15 15 DEFINING A METHOD It is good programming style to give methods meaningful names, indent the statements in the body of the method one level from the header, and include a paragraph of comments before each method describing the purpose of the method. This paragraph should document the data type and usage of each argument and the data type and purpose of the return value. Note that in the program DemoMethods.java there is a comment before every method definition. The comments are not included in these slides only so that the font is large enough to be seen in the classroom. You must include a comment before every method definition in the programs/methods you write for this course.

16 16 DEFINING A METHOD /** A void method that displays the letter grade that is the argument along with a message. @param grade The character representing the letter grade */ public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; }

17 17 DEFINING A METHOD A value-returning method named getGrade is defined below: public static int getGrade( ) { Scanner keyboard = new Scanner(System.in); int grade; System.out.print("Enter a grade "); grade = keyboard.nextInt( ); while (grade 100) // Validate grade { System.out.println("\nError: " + grade + " is not a valid grade."); System.out.println("Valid grades are in the range 0 through 100 inclusive.\n"); System.out.print("Enter a grade "); // Reprompt for and reread grade grade = keyboard.nextInt( ); } return grade; }

18 18 DEFINING A METHOD The method, named getGrade, returns the integer value that is the numeric grade entered by the user to the code that called the method. Notice that the return type of the method is int. public static int getGrade( ) { Scanner keyboard = new Scanner(System.in); int grade; System.out.print("Enter a grade "); grade = keyboard.nextInt( ); while (grade 100) // Validate grade { System.out.println("\nError: " + grade + " is not a valid grade."); System.out.println("Valid grades are in the range 0 through 100 inclusive.\n"); System.out.print("Enter a grade "); // Reprompt for and reread grade grade = keyboard.nextInt( ); } return grade; } The return type of getGrade is int.

19 19 DEFINING A METHOD The statement return grade; sends the integer value stored in grade to the code that called this method. public static int getGrade( ) { Scanner keyboard = new Scanner(System.in); int grade; System.out.print("Enter a grade "); grade = keyboard.nextInt( ); while (grade 100) // Validate grade { System.out.println("\nError: " + grade + " is not a valid grade."); System.out.println("Valid grades are in the range 0 through 100 inclusive.\n"); System.out.print("Enter a grade "); // Reprompt for and reread grade grade = keyboard.nextInt( ); } return grade; }

20 20 DEFINING A METHOD A value-returning method must have a return statement. The word return is a Java key word. The general format of a return statement is: return Expression; When a return statement is executed, the expression is evaluated and then the method ends execution and returns the value of the expression to the code that called the method. The return type declared in the method header must be the same type or a type compatible with the value returned by the method.

21 21 DEFINING A METHOD A void method may have a return statement of the following form: return; This statement ends the execution of the method and returns to the code that called the method.

22 22 DEFINING A METHOD A method of a structured program should have no more than one return statement. You may not have more than one return statement in any method you write for this class.

23 23 CALLING A METHOD A method executes when it is called. The main method is called automatically when the program is executed. We call methods by inserting method calls in our program. A method call consists of the name of the method followed by a parenthesized list of arguments. Arguments are values sent into the method.

24 24 CALLING A METHOD The method getGrade does not expect any input values, so it is called with an empty argument list. This method is called in the program DemoMethods.java when the following statement is executed: numericGrade = getGrade( );

25 25 CALLING A METHOD When a method is called, execution branches to the method and executes the statements in the body of the method. When the method has finished executing, execution goes back to the location of the method call.

26 26 PASSING ARGUMENTS TO A METHOD Some methods are designed to accept arguments. Arguments are values sent to a method. For example, the pow method of the Math class takes two arguments, a base and an exponent. The following statement calls this method with the arguments 2.0 and 3.0: result = Math.pow(2.0, 3.0);

27 27 PASSING ARGUMENTS TO A METHOD A method that accepts arguments has parameter variables to receive the arguments. A parameter is a variable that receives a value passed into a method. The names and data types of the method's parameters are specified in the parenthesized parameter list that follows the method name in the method header.

28 28 PASSING ARGUMENTS TO A METHOD The following is an example of the definition of a method that accepts a single argument: public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; }

29 29 PASSING ARGUMENTS TO A METHOD A parameter, of type char, named grade, is declared in the method displayGrade. This allows the method to accept an argument. public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; } This is the declaration of a parameter variable named grade. The data type of the parameter is char.

30 30 PASSING ARGUMENTS TO A METHOD The value of the argument passed to a method is copied into the method’s parameter variable.

31 31 PASSING ARGUMENTS TO A METHOD Example: The following statement, from the main method of DemoMethods.java, calls the method displayGrade with the argument letterGrade. The value in the variable letterGrade is copied into the parameter variable named grade. displayGrade(letterGrade); public static void displayGrade(char grade) The value of the argument from the method call is copied into the parameter variable that was declared in the method header.

32 32 LOCAL VARIABLES A local variable is a variable declared inside a method. Remember that the scope of a variable is the portion of the program where it may be accessed by its name. The scope of a local variable is from its declaration to the end of the block in which it is declared. Different methods can have local variables with the same name, because these variables have different scopes. These variables are distinct and are stored at different addresses in memory.

33 33 LOCAL VARIABLES In this class, you must declare all variables locally (inside some method). You will send data items to other methods utilizing arguments/parameters.

34 34 MORE ON PASSING ARGUMENTS TO A METHOD Scope of a Parameter Variable The scope of a parameter is the body of the method where it is declared.

35 35 A PROGRAM COMPOSED OF MULTIPLE METHODS ***See the pseudocode and the source code for the program DemoMethods.java on webct

36 36 MORE ON PASSING ARGUMENTS TO A METHOD Notice that in the method call, we do not include the data type of the argument in the parentheses. displayGrade(letterGrade); public static void displayGrade(char grade) { System.out.println("\nThe grade assigned is " + grade + "."); if (grade == 'A') { System.out.println("Fantastic!"); } else if (grade == 'B') { System.out.println("Great job!"); } return; } The data type of the argument should not be included in the parentheses of the method call. The method header specifies the number and data types of the values passed into the method. Here we are declaring a parameter variable to store the value passed into the method.

37 37 MORE ON PASSING ARGUMENTS TO A METHOD Argument and Parameter Data Type Compatibility Any expression with a value that could be assigned to a variable of the parameter's data type may be used as the argument in the method call.

38 38 MORE ON PASSING ARGUMENTS TO A METHOD Argument and Parameter Data Type Compatibility Example: Both parameters of the pow method of the Math class are doubles. Below, the first argument is the int 5. This is ok, because we can assign an int to a double. Java automatically does the widening conversion. The sqrt method returns a double, so the second argument and its’ corresponding parameter variable have the same type. double x, y = 9; x = Math.pow(3 + 2, Math.sqrt(y)); // Raises 5 to the 3rd power System.out.println(x); // Displays 125.0

39 39 MORE ON PASSING ARGUMENTS TO A METHOD Argument and Parameter Data Type Compatibility When you pass an argument to a method, you must ensure that the argument’s data type is compatible with the data type of the parameter. Java will automatically perform widening conversions. This means that if the argument is of a lower-ranking data type than the parameter, the argument will automatically be converted to the parameter's data type. For example, when an integer argument is passed into a parameter variable of type double, a copy of the integer value is made in the encoding scheme of a double, and this value is then copied into the parameter variable.

40 40 MORE ON PASSING ARGUMENTS TO A METHOD Argument and Parameter Data Type Compatibility Java does not automatically perform narrowing conversions, conversions to lower-ranking data types. If you try to pass an argument of a higher-ranking data type into a parameter variable, a compiler error occurs. You may use the cast operator to manually specify a conversion to a lower-ranking data type.

41 41 MORE ON PASSING ARGUMENTS TO A METHOD Passing Multiple Arguments to a Method If a method has multiple parameters, the parameters are separated by commas in the method header. Each parameter in a parameter list must have a data type listed before its name in the method header. For example, the header for the pow method of the Math class is similar to the following: public static double pow(double base, double exp) The parameters are separated by commas. Even though base and exp are both type double, the data type must be included for each parameter variable.

42 42 MORE ON PASSING ARGUMENTS TO A METHOD Passing Multiple Arguments to a Method A parameter list is an ordered list. The values of the arguments are associated with the parameters in order from left-to-right. Example: result = Math.pow(6.2, 5); public static double pow(double base, double exp)

43 43 MORE ON PASSING ARGUMENTS TO A METHOD Arguments Are Passed by Value In Java, arguments of primitive data types are passed by value. This means that only a copy of the argument's value is passed into the parameter. The storage allocated for a parameter is separate and distinct from the storage allocated for the arguments passed by the calling method. Any changes made by the method to the parameter do not affect the argument's value. ***See Code Listing 5-6 of the text. The source code for this program is on the CD that came with the text as PassByValue.java


Download ppt "11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms."

Similar presentations


Ads by Google