Methods Chapter 5 Programs x Method Correct Test


















![Ambiguous Invocation public class Ambiguous. Overloading { public static void main(String[] args) { System. Ambiguous Invocation public class Ambiguous. Overloading { public static void main(String[] args) { System.](https://slidetodoc.com/presentation_image_h2/9d7ff95aa8c42c2b881aac0c92e114fb/image-19.jpg)




















- Slides: 39

Methods Chapter 5 Programs: x. Method. Correct Test. Max Test. Pass. By. Value Y. Daniel Liang

Methods Objectives To learn the benefits of methods F To create and invoke methods F To understand the role of arguments in a method F To learn to pass parameters to a method F F To use method overloading and know ambiguous overloading F To understand the scope of local variables F To learn the concept of method abstraction Y. Daniel Liang

Creating a Method A method is a collection of statements that are grouped together to perform an operation. Method Structure Y. Daniel Liang

Creating a Method, cont. • parameter profile refers to the type, order, and number of the parameters of a method. • method signature is the combination of the method name and the parameter profiles. • The parameters defined in the method header are known as formal parameters. Y. Daniel Liang

Creating a Method, cont. • When a method is invoked, its formal parameters are replaced by variables or data, which are referred to as actual parameters. Y. Daniel Liang

Declaring Methods public static int max(int num 1, int num 2) { if (num 1 > num 2) return num 1; else return num 2; } Y. Daniel Liang

Calling Methods Example 4. 1 Testing the max method This program demonstrates calling a method max to return the largest of the int values Test. Max Y. Daniel Liang

Calling Methods, cont. Y. Daniel Liang

Calling Methods, cont. Y. Daniel Liang

CAUTION A return statement is required for a non void method. The following method is logically correct, but it has a compilation error, because the Java compiler thinks it possible that this method does not return any value. public static int x. Method(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return – 1; } To fix this problem, delete “if (n<0)” in the code so that the compiler will see a return statement to be reached regardless of how the if statement is evaluated - e. g. , else return -1; See programs x. Method. java and x. Method. Correct. java Y. Daniel Liang

Passing Parameters public static void n. Println(String message, int n) { for (int i = 0; i < n; i++) System. out. println(message); } Caution: The actual parameter must match the formal parameters in order, number, and compatible type, as defined in the method signature. Compatible type means that you can pass an actual parameter to a formal parameter without explicit casting. Y. Daniel Liang

Pass by Value When you invoke a method with parameters, a copy of the value of the actual parameter is passed to the method. This is referred to as pass by value. The actual variable outside the method is not affected, regardless of the changes made to the formal parameter inside the method. Test. Pass. By. Value. java Y. Daniel Liang

Pass by Value Example 4. 2 Testing Pass by value This program demonstrates passing values to the methods. Test. Pass. By. Value Y. Daniel Liang

Pass by Value, cont. Y. Daniel Liang

Overloading Methods You may create a second method from an existing method with the same name. Then change the data type of the parameters for the second method. This is called overloading a method. Y. Daniel Liang

Overloading Methods Example 4. 3 Overloading the max Method public static double max(double num 1, double num 2) { if (num 1 > num 2) return num 1; else return num 2; } Test. Method. Overloading Y. Daniel Liang

Overloading Methods Example 4. 3 Overloading the max Method Call max with int parameters public static int max(int num 1, int num 2) { if (num 1 > num 2) return num 1; else return num 2; } Test. Method. Overloading Y. Daniel Liang

Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a method, but the compiler cannot determine the most specific match. This is referred to as ambiguous invocation. Ambiguous invocation is a compilation error. Y. Daniel Liang
![Ambiguous Invocation public class Ambiguous Overloading public static void mainString args System Ambiguous Invocation public class Ambiguous. Overloading { public static void main(String[] args) { System.](https://slidetodoc.com/presentation_image_h2/9d7ff95aa8c42c2b881aac0c92e114fb/image-19.jpg)
Ambiguous Invocation public class Ambiguous. Overloading { public static void main(String[] args) { System. out. println(max(1, 2)); } public static double max(int num 1, double num 2) { if (num 1 > num 2) return num 1; else return num 2; } public static double max(double num 1, int num 2) { if (num 1 > num 2) return num 1; else return num 2; Y. Daniel Liang

Scope of Local Variables A local variable: a variable defined inside a method. Scope: the part of the program where the variable can be referenced. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared before it can Y. be used. Daniel Liang

Scope of Local Variables, cont. You can declare a local variable with the same name multiple times in different non-nesting blocks in a method, but you cannot declare a local variable twice in nested blocks. Thus, the following code is correct. Y. Daniel Liang

Scope of Local Variables, cont. // Fine with no errors public static void correct. Method() { int x = 1; int y = 1; // i is declared for (int i = 1; i < 10; i++) { x += i; } // i is declared again for (int i = 1; i < 10; i++) { y += i; } Y. Daniel Liang

Scope of Local Variables, cont. // Will cause a compilation error because x is declared in the for loop body block, which is nested inside the method body where another x is declared. public static void incorrect. Method() { int x = 1; int y = 1; for (int i = 1; i < 10; i++) { int x = 0; // will cause a compilation error x += i; } } If a variable is declared as a method parameter, it cannot be redeclared inside the method. The Y. scope of a method Daniel Liang

Method Abstraction The separation of the use of a method from its implementation. The client can use a method without knowing how it is implemented. The details of the implementation are encapsulated in the method and hidden from the client who invokes the method. This known as information hiding or encapsulation. If you change the implementation, the client program will not be affected provided that you do not change the method signature Y. Daniel Liang

Static Variables, Constants, and Methods An instance variable is tied to a specific instance of the class. It is not shared among objects of the came class. Example: Circle circle 1 = Circle(); Circle circle 2 = Circle(); The radius in Circle 1 is independent of the radius in circle 2. Its radius is stored in a different memory locations. Changes made to Circle 1’s radius do not affect Circle 2’s radius, and vice versa Y. Daniel Liang

Static Variables, Constants, and Methods contd. An static variable is defined when you want all the instances of a class to share data. Static variables store values for the variable s in a common memory location. Because of this common location, all objects of the same class are affected if one object changes the value of a static variable. Java supports static methods as well as static variables. Static methods can be called without creating an instance (object) of the class. Y. Daniel Liang

Caution; Static variables and methods can be used from instance or static methods in the class. However instance variables and methods can only be used from instance methods, not from static methods. Since static variables and methods belong to the class as a whole and not to particular objects. See code on next slide. Also, see program FOO Y. Daniel Liang

public class Foo { int i = 5; static int k = 2; public static void main(String[] args) { // int j = i; // Wrong because i is an instance variable // m 1(); // Wrong because m 1() is an instance method } public void m 1() { // Correct since instance and static variables and methods // can be used in an instance method i = i + k + m 2(i, k); } public static int m 2(int i, int j) { return (int)(Math. pow(i, j)); } } Y. Daniel Liang

Method Abstraction You can think of the method body as a black box that contains the detailed implementation for the method. Y. Daniel Liang

Instance Variables, and Methods Instance variables belong to a specific instance. Instance methods are invoked by an instance of the class. Y. Daniel Liang 30

Methods What is System. out. println? It is a method: a collection of statements that performs a sequence of operations to display a message on the console. It can be used even without fully understanding the details of how it works. It is used by invoking a statement with a string argument. The string argument is enclosed within parentheses. In this case, the argument is "Welcome to Java!" You can call the same println method with a different argument to print a different message. Y. Daniel Liang 31

main Method The main method provides the control of program flow. The Java interpreter executes the application by invoking the main method. The main method looks like this: public static void main(String[] args) { // Statements; } Y. Daniel Liang 32

The exit Method Use Exit to terminate the program and stop all threads. Example: System. exit(0); NOTE: When your program starts, a thread is spawned to run the program. When the show. Message. Dialog is invoked, a separate thread is spawned to run this method. The thread is not terminated even when you close the dialog box. To terminate thread, you have to invoke the exit method. Y. Daniel Liang 33

Displaying Text in a Message Dialog Box you can use the show. Message. Dialog method in the JOption. Pane class. JOption. Pane is one of the many predefined classes in the Java system, which can be reused rather than “reinventing the wheel. ” Run Y. Daniel Liang 34

The show. Message. Dialog Method JOption. Pane. show. Message. Dialog(null, "Welcome to Java!", “Display Message", JOption. Pane. INFORMATION_MESSAGE)); Y. Daniel Liang 35

Two Ways to Invoke the Method There are several ways to use the show. Message. Dialog method. For the time being, all you need to know are two ways to invoke it. One is to use a statement as shown in the example: JOption. Pane. show. Message. Dialog(null, x, y, JOption. Pane. INFORMATION_MESSAGE)); where x is a string for the text to be displayed, and y is a string for the title of the message dialog box. Y. Daniel Liang 36

Two Ways to Invoke the Method The other is to use a statement like this: JOption. Pane. show. Message. Dialog(null, x); where x is a string for the text to be displayed. Y. Daniel Liang 37

Benefits of Methods • Write once and reuse it any times. • Information hiding. Hide the implementation from the user. • Reduce complexity. Y. Daniel Liang

Java IDE Tools (Integrated Development Entvironment) Used to rapidly develop Java Programs: edit, compile, build, debug , gain online help in an integrated graphical interface F Forte by Sun Micro. Systems F Text. Pad F Borland JBuilder F Microsoft Visual J++ F Web. Gain Café F IBM Visual Age for Java Y. Daniel Liang 39