Download presentation
Presentation is loading. Please wait.
Published byChastity Foster Modified over 9 years ago
1
COSC236 Modularity1 Top-Down Design Design before code most programs so far have been simple, less than one page in length most problems are not so simple top-down design-identify first the major tasks and then further subtasks within them stepwise refinement divide and conquer
2
COSC236 Modularity2 Procedural decomposition all tasks can be subdivided and further subdivided into subtasks goal - can easily construct code for each subtask each module constructed and tested as unit Black box Stubbing in (write dummy methods), always have something working Single entry, single exit Short enough to be easily read and modified Long enough top perform a single method
3
COSC236 Modularity3 Procedural decomposition subroutines, subprograms, or procedures In Java these subparts are called methods. Advantages of using methods: –Different people can work on different subtasks when producing very large programs. –Block of code can be used more than once - the final program is more modular. –Each method performs some task - can work as a black box
4
COSC236 Modularity4 Methods - Overview Every Java program must have a method called main Program execution always begins with method main method definitions can occur in any order
5
COSC236 Modularity5 2 types of methods in java 1.Predefined 2.User created –Value-returning –void
6
Math class > import static java.lang.Math.*; > E 2.718281828459045 > PI 3.141592653589793 > sqrt (25) 5.0 > abs(-1) 1 > ceil (5.6)//double arg, returns smallest integer that is not less than x 6.0 > floor (5.6)//double arg, returns largest integer that is less than x 5.0 > log(2) 0.6931471805599453 COSC236 Modularity6
7
Math class > import static java.lang.Math.*; > log10(2) 0.3010299956639812 > max(23.6,-4) 23.6 > min(23.6,-4) -4.0 > pow(2,3) 8.0 > round(24.83) 25 > sqrt(1024) 32.0 > cos(0) 1.0 COSC236 Modularity7
8
Class Character isDigit(ch) returns true or false –isDigit(‘a’) returns false, isDigit(‘8’) returns true isLetter(ch) returns true or false –isLetter(‘a’) returns true, isLetter(‘8’) returns false isLowerCase(ch) returns true or false –isLowerCase(‘a’) returns true, isLowerCase(‘A’) returns false isUpperCase(ch) returns true or false –isUpperCase(‘A’) returns true, isUpperCase(‘a’) returns false isSpaceChar(ch) returns true or false –isSpaceChar(‘ ’) returns true, isSpaceChar(‘A’) returns false isWhiteSpace(ch) returns true or false –isWhiteSpace(‘ ’) returns true, isWhiteSpace(‘\n’) returns true toLowerCase(ch) returns lowercase equivalent or ch –toLowerCase(‘A’) returns ‘a’, toLowerCase(‘*’) returns * toUpperCase(ch) returns uppercase equivalent or ch –toUpperCase(‘a’) returns ‘A’, toUpperCase(‘*’) returns * COSC236 Modularity8
9
Using predefined methods Java automatically imports classes from the package java.lang Class methods can be static or nonstatic Class methods can be public or nonpublic A public and static method can be called using the name of the class, the dot operator, the method name, and the appropriate parameters Exa: Math.methodName(parameters) Math.pow(2.5,3.5); COSC236 Modularity9
10
Simpler use of public static methods Static import statements To use any (public) static method of a class –import static pkgName.ClassName.*; To use a specific method of the class –import static pkgName.ClassName.methodname; Allow omission of the class name and the dot operator import static java.lang.Math.*; pow(2.5,3.5) as opposed to Math.pow(2.5,3.5); COSC236 Modularity10
11
User defined methods- value-returning requires 1.Name of the method 2.The number of parameters 3.The data type of each parameter 4.The data type of the value computed (method type) 5.code Use the value: Save the value Use the value Print the value COSC236 Modularity11
12
Naming value-returning methods Should use a noun or an adjective and the name should suggest a value. Examples: maxScore finalBalance square cube squareRoot isPalindrome isValid COSC236 Modularity12
13
Example method public static int abs (int number) { if (number < 0) number = -number; return number; } COSC236 Modularity13
14
Invoking the method Save the value –y = abs(-2); Use the value –a = abs(x) + 25; Print the value –System.out.println(abs(h)); COSC236 Modularity14
15
Parameters or arguments Data passed between methods Formal parameter- variable declared in the method heading (generalized parameter) Actual parameter (argument) – variable or expression listed in a call to a method –Could be constant Formal parameter and actual parameter names do not have to match COSC236 Modularity15
16
Syntax: Value-returning method modifier(s) returnType methodName(formal param list) { Statements //body } Modifier – visibility –public – can be accessed outside the class –private – cannot be used outside the class –static, abstract, final (more later) COSC236 Modularity16
17
Method syntax Syntax: Formal parameter list –dataType identifier, dataType identifier.. –Can be empty Syntax: Method call –methodName(actual parameter list) Syntax: Actual parameter list –expr. or variable, expr. or variable,… The number of actual parameters, and their data types must match formal parameter list COSC236 Modularity17
18
return Statement Syntax: return statement –return expr; –Type must match return type of method COSC236 Modularity18
19
//version 1 public static double larger(double x, double y) { double max; if (x >= y) max = x; else max = y; return max; } COSC236 Modularity19
20
// version 2 public static double larger(double x, double y) { if (x >= y) return x; else return y; } //version 3 public static double larger(double x, double y) { if (x >= y) return x; return y; } COSC236 Modularity20
21
Sample calls maxNum = larger(x,y); System.out.println(larger(a,b)); result = larger(f,30) *3; COSC236 Modularity21
22
COSC236 Modularity22 boolean method public static void main(String[] args) { double angleA, angleB, angleC; System.out.println ( "Enter 3 values for angles: "; console.nextDouble(angleA); console.nextDouble(angleB); console.nextDouble(angleC ); while(angleA <= 0 || angleB <= 0 || angleC <= 0) { System.out.println("ERROR! Should be positive. Reenter: “); console.nextDouble(angleA); console.nextDouble(angleB); console.nextDouble(angleC); } if (IsTriangle(angleA,angleB,angleC))//method call System.out.println("The three angles form a valid triangle.”); else System.out.println("These angles do not form a triangle.”); } // method definition public static boolean IsTriangle (float a, float b, float c) { //remember how to test for equality when working with float! return (fabs(a + b + c - 180.0) < 0.00000001); }
23
void methods modifier(s) void methodName(formal param list) { Statements } Call: methodName(actual params); COSC236 Modularity23
24
COSC236 Modularity24 Naming void methods Begin with verb make it look like a command or an instruction to the computer Example: printLines(), openFile(), getData(), printData(), generateArray(), etc.
25
COSC236 Modularity25 Example #1: public class Banner { public static void main (String[] args) { printStars(); System.out.println(“*******Annual *********”); printStars(); System.out.println(“***** Spring Sale *****”); printStars(); } //*********************************************************** // This method prints 2 lines with 30 stars each //*********************************************************** public static void printStars() { for (int lines = 1; lines <= 2; lines ++) { for (int stars = 1; stars <= 30; stars++) System.out.print(“*”); System.out.println(); } } }
26
public class Banner { public static void main (String[] args) { printSymbol(‘!’, 2); System.out.println(“*******Annual *********”); printSymbol(‘*’,10); System.out.println(“***** Spring Sale *****”); printSymbol(‘!’,2); } //*********************************************************** // This method prints numRows of 30 symbols //*********************************************************** public static void printSymbol(char symbol, int numRows) { for (int lines = 1; lines <= numRows; lines ++) { for (int cnt = 1; cnt <= 30; cnt++) System.out.print(symbol); System.out.println(); } } } COSC236 Modularity26
27
COSC236 Modularity27 void method call methodName(actual parameter list); control passed to method at its definition in calling program temporary memory is set up (stores params and vars) Begins with first statement in the called method’s body Executes until return or } control returns to the line following the method call call must match number, order, data type of parameters May have 0,1, or many parameters Parentheses required Multiple parameters are separated by commas
28
COSC236 Modularity28 The return statement return 0; //not used with void methods return; // returns no value –valid ONLY with void methods –can appear anywhere in the body of the method –causes control to exit the method immediately and transfers control back to caller. –Use in special cases only (the programs are confusing, hard to follow and more difficult to debug). –Single-entry single-exit approach is generally better
29
COSC236 Modularity29 EXAMPLE: public static void main(String[] args) { float roomLength,roomWidth; System.out.println("Enter length and width" ); roomLenth = console.nextDouble(); roomWidth = console.nextDouble(); dispArea(roomLength,roomWidth); } public static void dispArea(float length, float width) { int area; area = length * width; System.out.println(“Area is “ + area); }
30
COSC236 Modularity30 Example: public static void main (String[] args) { int num1, num2; System.out.println(“Enter two numbers” ) num1 = console.nextInt(); num2 = console.nextInt(); displaySum(num1,num2); System.out.println(“sum is “ + sum(num1,num2)); } public static void displaySum (int num1,int num2) // note the name begins with a verb { int sum; sum = num1 + num2; System.out.println(“sum is “ + sum); } public static int sum (int num1,int num2) // name is a noun { int sum; sum = num1 + num2; return sum;// return num1 + num2; }
31
COSC236 Modularity31 Scope of Identifiers A variable can generally be used at any point after it has been declared. The one exception to this rule is a variable declared in the control portion of a for loop, which can only be used within the loop. This is an example of scope, which identifies the range over which any identifier (e.g., variable or method) can be accessed. Each method is a block Block -set of statements enclosed within braces Any method can declare identifiers within its block. The scope of a variable spans from the point where it is declared to the end of the block where it was declared. Once we reach the brace bracket that closes the block, the variable can no longer be used. Local identifiers = identifiers declared within a block and not accessible outside of that block.
32
Consider the following code public static void scopeSample (double a) // scope of a begins { int b = 0; // scope of b begins... for (int c = 1;...) // scope of c begins { int d = 2; // scope of d begins... } // scope of c,d ends } // scope of a,b ends As you can see, our method included one parameter. The scope of a parameter is the entire method that uses the parameter, just as the scope of the variable in the for loop is the entire loop. COSC236 Modularity32
33
Local variables A local variable is used to store information that is relevant for the duration of the execution of one method A local variable will exists as long as the method in which they have been created is still running As soon as the method terminates (i.e., returns), all the local variables defined inside the method are destroyed. COSC236 Modularity33
34
COSC236 Modularity34 Scope of Identifiers Each method is a block Block -set of statements enclosed within braces Any method can declare identifiers within its block. The scope of a variable spans from the point where it is declared to the end of the block where it was declared. Once we reach the brace bracket that closes the block, the variable can no longer be used. Local identifiers = identifiers declared within a block and not accessible outside of that block. Global variables = identifiers declared outside of all the methods in a program No nesting of methods Within a method or a block, an identifier must be declared before it can be used Identifier can be declared anywhere inside a class Cannot use same identifier name in the outer block and inner block
35
scope An identifier, declared within a method or block is accessible: –Only within the block from the point at which it is declared until the end of the block –By those blocks that are nested within the blocks for (int count = 1; count < 10; count++) System.out.println(count); COSC236 Modularity35
36
scope An identifier, x, declared within a class and outside every method’s definition –If x is declared static, then it can be accessed within the method, assuming the method has no other identifier named x –If x is not declared static, then it cannot be accessed within a static method COSC236 Modularity36
37
Local identifiers exist only when the method is executing When the method is called (invoked) - memory space is created for its local identifiers When the method is finished (returns)- its local identifiers are destroyed. COSC236 Modularity37
38
COSC236 Modularity38 Example: public static void main (String[] args) { int x,y; x = 1; y = 2; System.out.println("x = " + x + " y = " + y); OutputX(); // method call OutputY(); // method call System.out.println("x = " + x + " y = " + y); return 0; } public static void OutputX() { int x; // local variable x = 3; System.out.println("x = " + x ); } public static void OutputY() { int y; // local variable y = 4; System.out.println(" y = " + y); } OutputX x OutputY y main x y
39
COSC236 Modularity39 void vs value-returning 1.When returning more than one value or modify any of the caller's arguments - use void method 2.When I/O is required in the method - use void method 3.When returning just one value and the value is Boolean - use value returning method 4.When returning one value to be used immediately in an expression - use value returning method 5.When in doubt - use void. 6.If both void and value returning are acceptable, use the one you prefer.
40
COSC236 Modularity40 pass by value transfers a copy of the value of the actual parameter to a formal parameter. The method sees only this copy and cannot access the actual parameter itself. pass by value leads to two separate copies of the data: one in the actual parameter and one in the formal parameter. This protects the actual parameter from being modified Can also pass constants and arbitrary expressions to actual value parameter If formal argument is a primitive data type – pass by value
41
COSC236 Modularity41 public class DemoPassByValue { public static void main(String[] args) { // Part I - primitive data types int i = 25; System.out.println(i); // print it (1) iMethod(i); System.out.println(i); // print it (3) System.out.println("-----------------"); } public static void iMethod(int iTest) { iTest = 9; // change it System.out.println(iTest); // print it (2) } > java DemoPassByValue 25 9 25
42
Pass by reference formal parameter must be a reference parameter reference variable contains address use new to allocate memory for an object pass variable=> actual and formal point to same address changes to formal, change actual useful: –when you want to return more than one value –when the value of an actual object needs to be changed –when passing the address would save memory space and time COSC236 Modularity42
43
COSC236 Modularity43 public class DemoPassByReference { public static void main(String[] args) { // Part III - strings String s = "Java is fun!"; System.out.println(s); // print it (7) sMethod(s); System.out.println(s); // print it (9) } public static void sMethod(String sTest) { sTest = sTest.substring(8, 11); // change it System.out.println(sTest); // print it (8) } Java is fun! fun Java is fun!
44
precaution with strings Remember - the String class is immutable String str; str = "hello"; str 1500 "hello" str = "Hello There"; str 1800 "Hello There" anytime you use assignment with a String variable, new memory space is allocated also, the String class has no methods that allow you to change an existing string COSC236 Modularity44
45
COSC236 Modularity45 public class DemoPassByReference { public static void main(String[] args) { // Part II - objects and object references StringBuffer sb = new StringBuffer("Hello, world"); System.out.println(sb); // print it (4) sbMethod(sb); System.out.println(sb); // print it (6) System.out.println("-----------------"); } public static void sbMethod(StringBuffer sTest) { sTest = sTest.insert(7,"cruel "); // change it System.out.println(sTest); // print it (8) } Hello, world Hello, cruel world
46
import java.awt.*; public class DemoPassByReference { public static void main(String[] args) { Point p = new Point (1,2); System.out.println(p); testMethod(p); System.out.println(p); } public static void testMethod(Point p) { System.out.println(p); p.setLocation(3,4); System.out.println(p); } COSC236 Modularity46
47
COSC236 Modularity47 Scope Rules Avoid (don't use) global data method name has global scope formal parameters are local to method. global variables visible from declaration to the end of the file. Local variable (or constant) scope extends from declaration to the end of the block where declared. local identifiers have name precedence.
48
Preconditions and Postconditions precondition –assertion describing everything that the method requires to be true before method is invoked postcondition –describes the state at the moment the method finishes executing the caller is responsible for ensuring the precondition, and the method code must ensure the postcondition
49
COSC236 Modularity49 Testing and debugging - stubs and drivers Work Incrementally, Keep Something Working Stub –a dummy method with a very simple body –often just an output statement that this method was reached, and a return value (if required) of the correct type. –same name and parameter list. Driver –a simple main method used to call a method that is being tested. –Allows direct control of the testing process. Both stubs and drivers allow testing different situations and combinations that may reveal errors.
50
Introduction to Method Overloading methods with the same name, different formal parameter list or different return type public void methodXYZ() public void methodXYZ(int x, double y) public void methodXYZ(double one, int y) public void methodABC(int x, double y) public int methodABC(int x, double y) COSC236 Modularity50
51
int larger(int x, int y) char larger(char first, char second) double larger(double u, double v) String larger(String first, String second) COSC236 Modularity51
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.