Presentation is loading. Please wait.

Presentation is loading. Please wait.

COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.

Similar presentations


Presentation on theme: "COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004."— Presentation transcript:

1 COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004

2 Anatomy of a Class A class contains data declarations and method declarations int width; int length; Data declarations Method declarations (operations)

3 Writing a class public class Rectangle { // data members private int width; private int length; // methods public double computeArea() … public static void main() … }

4 Why Use Methods? To divide complex programs into manageable pieces Abstraction –provide an operation to be performed on an object (ex: computeArea) Code Re-use –write a small piece of code that can be used (called) multiple times (saves typing)

5 Methods Pre-defined methods –provided by Java standard library –we've used these before –Math class (Math.pow, Math.sqrt,...) –Integer class (Integer.parseInt,...) User-defined methods –you write these

6 Method as a Black Box METHOD Input parameters Internal data members of the class Return value A method can use input parameters and internal data members of the class It may modify the value of internal data members It may also return a value

7 Control Flow Program control flow –execution always begins with the first statement in the method main –other methods execute only when called Method control flow –when a method is invoked, the flow of control jumps to the method and the computer executes its code –when complete, the flow of control returns to the place where the method was called and the computer continues executing code Test this with the debugger!

8 Example: Rectangle.java

9 Using Methods What You Need To Know 1.Name of the method 2.Number of parameters 3.Data type of each parameter 4.Data type of value computed (returned) by the method 5.The code required to accomplish the task

10 Method Declaration Specifies the code that will be executed when the method is invoked (or called) Located inside a class definition Contains –method header –method body

11 Method Header public static int countCharInWord (char ch, String word) method name return type formal parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter A method declaration begins with a method header visibility modifiers

12 Return Value Value-returning methods –The method returns the result of some operations –Like mathematical functions –Return one single value Void methods –Perform operations but return no value

13 Value-Returning Methods Think mathematical function f(x) = 2x + 5f(x, y) = 2x + y f(1) = 7f(1, 5) = 7 f(2) = 9f(2, 3) = 7 f(3) = 11f(3, 1) = 7 Can have multiple arguments (parameters) Only one result of the function

14 Value-Returning Methods Uses Save the value for future calculation Use the value in a calculation Print the value x = Math.pow (y, 2); z = a + Math.pow (y, 2) + x; System.out.println (Math.pow (y, 2));

15 int number = countCharInWord ('e', "Heels"); 2 Return Type Indicates the type of value that the method evaluates to: –primitive data type –class name –void  reserved word indicating that nothing is returned When a value is returned, the method call is replaced with the returned value

16 The return Statement Tells the computer to "return" back to where the call was originally made. Specifies the value that will be returned return expression; The data type of expression must match the method's return type Methods with return types of void usually don't (but can) have a return statement Value-returning methods must have at least one return statement

17 Using return public static double larger (double x, double y) { double max; if(x >= y) max = x; else max = y; return max; } public static double larger (double x, double y) { if(x >= y) return x; else return y; } These are equivalent methods.

18 Example: Rectangle.java Add computePerimeter( )

19 Void Methods Do not return a value Have a return type of void Similar in structure to value-returning methods Call to method is always a stand-alone statement Can use return statement to exit method early

20 Example: Rectangle.java Add printPerimeter( )

21 The main Method The main method looks just like all other methods public static void main (String[] args) modifiersreturn type method name parameter list

22 Method Body The method header is followed by the method body public static int countCharInWord (char ch, String word) { int count = 0; for (int i = 0; i<word.length(); i++) { if (word.charAt(i) == ch) { count++; } return count; } The return expression must be consistent with the return type ch and word are local data They are created each time the method is called, and are destroyed when it finishes executing

23 Example: Largest.java Read a sequence of numbers Print the max

24 Parameters Each time a method is called, the actual parameters in the call are copied into the formal parameters int num = countCharInWord ('e', "Heels"); { int count = 0; for (int i = 0; i<word.length(); i++) { if (word.charAt(i) == ch) { count++; } return count; } public static int countCharInWord (char ch, String word)

25 printStars (35); printStars (30 + 5); int num = 35; printStars (num); Parameters Formal parameters –variable declarations in the method header –automatic local variables for the method Actual parameters –actual values that are passed to the method –can be variables, literals, or expressions

26 Parameters Primitive Data Type Variables If a formal parameter is a variable of a primitive data type, can it be modified inside a method? –The value from the actual parameter is copied –There is no connection between variables inside the method and outside –Conclusion: it cannot be modified!!

27 Example: Largest.java Modify the values inside the comparison method

28 Parameters Reference Variables If a formal parameter is a reference variable, can the object be modified inside a method? –The address from the actual parameter is copied –The local reference variable points to the same object –Conclusion: it can be modified!!

29 Primitive Data Types What if we want to modify a variable of a primitive data type inside a method? –Encapsulate it in a class –Example: IntClass (ch. 6, p. 306) IntClass is a class suggested in the book, but it is not a built-in class in Java!!!

30 Data Scope The scope of data is the area in a program in which that data can be used (referenced) Data declared at the class level can be used by all methods in that class Data declared within a method can be used only in that method –also called local data Key to determining scope is to look for blocks of code (surrounded by { } ) –variables declared inside { } cannot be used outside –recall the problems some had with variables declared inside if statements

31 Data Scope Example public class Rectangle { // variables declared here are class-level // available in all methods in Rectangle class public int computeArea() { // variables declared here are method-level // only available in computeArea() } public void print() { // variables declared here are method-level // only available in print() }

32 Overloading Methods Overloading - the process of using the same method name for multiple methods The signature of each overloaded method must be unique –number of parameters –type of the parameters –not the return type of the method, though The compiler determines which version of the method is being invoked by analyzing the parameters

33 Overloading Methods public static double tryMe (int x) { return x +.375; } Version 1 public static double tryMe (int x, float y) { return x*y; } Version 2 Invocation result = tryMe (25, 4.32)

34 Overloaded Methods println Example The println method is overloaded: println (String s) println (int i) println (double d) and so on... The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total);

35 Example: PrintStars.java

36 To do Tomorrow: practice for mid-term –Bring laptops –Collect questions Pick examples that we have done so far and convert parts of the code to methods –Binary.java (homework 2) –AverageKeyboard.java –AsteriskPattern.java –…


Download ppt "COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004."

Similar presentations


Ads by Google