tailieunhanh - Lecture Introduction to Java programming - Chapter 5: Methods

After completing this unit, you should be able to: To define methods, to invoke methods with a return value, to invoke methods without a return value, to pass arguments by value; to develop reusable code that is modular, easy to read, easy to debug, and easy to maintain;. | Chapter 5 Methods Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. Problem int sum = 0; for (int i = 1; i Problem int sum = 0; for (int i = 1; i Solution public static int sum(int i1, int i2) { int sum = 0; for (int i = i1; i Objectives To define methods, invoke methods, and pass arguments to a method (§). To develop reusable code that is modular, easy-to-read, easy-to-debug, and easy-to-maintain. (§). To use method overloading and understand ambiguous overloading (§). To design and implement overloaded methods (§). To determine the scope of variables (§). To know how to use the methods in the Math class (§§). To learn the concept of method abstraction (§). To design and implement methods using stepwise refinement (§). Defining Methods A method is a collection of statements that are grouped together to perform an operation. Method Signature Method signature is the combination of the method name and the parameter list. Formal Parameters The variables defined in the method header are known as formal parameters. Actual Parameters When a method is invoked, . | Chapter 5 Methods Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. Problem int sum = 0; for (int i = 1; i Problem int sum = 0; for (int i = 1; i Solution public static int sum(int i1, int i2) { int sum = 0; for (int i = i1; i <= i2; i++) sum += i; return sum; } public static void main(String[] args) { ("Sum from 1 to 10 is " + sum(1, 10)); .