Methods, Object Oriented Programming(OOP)
Transcription
Methods, Object Oriented Programming(OOP)
CS 171000 – Lecture 1 Algorithms and Object Oriented Programming Reading: Chapter 1.1-1.2 Anca Doloc-Mihu August 29th, 2016 1 Contents Algorithms Data types Methods 2 What is an Algorithm? • An algorithm is a method for solving a problem expressed as a sequence of steps that is suitable for execution by a computer (machine). • Can be expressed in –natural languages –Flowcharts –Pseudocode –programming languages 3 What is an Algorithm? Example of algorithm: determine if a number n is a prime number pseudocode: k = 2; As long as k < n do { 1. Divide n by k 2. If n is divisible by k, then return NO 3. Otherwise, increase k by 1 } return YES Java //wrong! int k = 2; while ( k++< n ) { if ( n%k == 0) return false; } return true; //correct int k = 1; while ( ++k< n ) { if ( n%k == 0) return false;} return true; 4 What is a data structure •A data structure is a way for organizing and accessing data (example data on next slide) •Example data structures –Arrays –Trees, Graphs •We will learn –Fundamental data structures and their operations –How to implement some of them –How to evaluate them and decide when to use what –How to use Java’s provided data structures Tree 5 A day on the internet •294 billion emails are sent •2 million blog posts •172 million different people visit facebook –532 million statuses are being updated –250 million photos are uploaded •Twitter: 40 million •LinkedIn: 22 million •22 million hours of TV shows and movies are watched on Netflix •864,000 hours of video are uploaded to YouTube •18.7 million hours of music is streamed on Pandora •35 million apps are downloaded •2 million search queries per minute on Google •…. By Li Xiong 6 Algorithms and data structures Algorithm + Data Structure = Program –An algorithm must use some data structure to store its information –An algorithm manipulates the data in the data structures in various ways To write a program –Design the data structures to store the information –Design the algorithm that uses the information to solve the problem –Implement the algorithm 7 Algorithms and data structures “ I will, in fact, claim that the difference between a bad programmer and a good one is whether he considers his code or his data structures more important. Bad programmers worry about the code. Good programmers worry about data structures and their relationships. ” — Linus Torvalds (creator of Linux) 8 Good Algorithms and Data Structures Good algorithms and data structures are keys to write a good program for solving a problem Eg: social network (maintaining and searching many profiles) Need ways to measure “goodness” of data structures and algorithms Algorithm analysis –Runtime analysis, Big-O notation Other goodness metrics: space usage, power 9 Data Types Primitive types –Integers, with arithmetic operations: byte, short, int, long –Real numbers, with arithmetic operations: float, double –Booleans, with {true, false} values and logical operations: boolean –Characters: char Reference types –Class types, array types –Special null types 10 Variables A variable is a name for a location in memory used to hold a data value. –Name (identifier), type, and value Using a variable –Declaring a variable – type and name int i; Instructs the compiler to reserve a portion of main memory to hold a particular type of value referred by a particular name –Assign a value to a variable –Use a variable in an expression i = 1; i+ = 1; i++; •A variable cannot be used if it is not declared or initialized •The left hand side of the assignment operator is always a variable and the right hand side is an expression 11 Primitive Data Types vs. Object data types Variables of primitive data types store the actual value Variables of object types store the reference to the object • If it does not reference any object, it holds a special value: null Circle c; c = new Circle(1); double r = c.getRadius(); 12 Comparison Operators Operator Name < <= > >= == != less than less than or equal to greater than greater than or equal to equal to not equal to Comparing objects == compares references – Check whether an object variable contains a null reference equals() method compares contents 13 Questions??? Nearpod.com/student Enter code: Answer questions! 14 Conditionals if (booleanExpression) { statement(s); } if (booleanExpression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } 15 World Without Loops is Painful… System.out.println(“I will write good code!”); System.out.println(“I will write good code!”); System.out.println(“I will write good code!”); System.out.println(“I will write good code!”); System.out.println(“I will write good code!”); System.out.println(“I will write good code!”); 16 int count=0; while (count < 100){ System.out.println(“I will write good code!”); count++; } Loops: while while (loop-continuation -condition) { // loop-body; Statement(s); } count = 0; Loop Continuation Condition? false (count < 100)? true Statement(s) (loop body) (A) false true System.out.println("I’ll write good code!"); count++; (B) 17 Loops: do-while int count=0; do{ System.out.println(“I will write good code!”); count++; } while(count < 100); do { //loop body Statement(s); } while (loop-continuation-condition); 18 Loops: for for(int count=0; count < 100; count++ ){ System.out.println(“I will write good code!”); } for (initial-action; loop-condition; action-after-each-iteration) { // loop body; Statement(s); } 19 Which loop to use? 20 Pair grouping Questions??? Each group/pair: Nearpod.com/student Enter code: Answer questions! 21 Low-level programming: computer programs manipulate primitive types such as numbers and characters Methods: Encapsulate routine computations to black boxes Object-oriented programming: Encapsulate data fields and methods to black boxes 22 Example: Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. int sum = 0; for (int i = 1; i <= 10; i++) sum += i; System.out.println("Sum from 1 to 10 is " + sum); sum = 0; for (int i = 20; i <= 30; i++) sum += i; System.out.println("Sum from 20 to 30 is " + sum); sum = 0; for (int i = 35; i <= 45; i++) sum += i; System.out.println("Sum from 35 to 45 is " + sum); 23 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) { System.out.println("Sum from 1 to 10 is " + sum(1, 10)); System.out.println("Sum from 20 to 30 is " + sum(20, 30)); System.out.println("Sum from 35 to 45 is " + sum(35, 45)); } 24 Defining Methods A method is a collection of statements that are grouped together to perform an operation. Define a method modifier method header return value type Invoke a method method name formal parameters int z = max(x, y); public static int max(int num1, int num2) { actual parameters (arguments) int result; method body if (num1 > num2) result = num1; else result = num2; return result; parameter list method signature return value } 25 Method Signature Method signature is the combination of the method name and the parameter list. Define a method modifier method header return value type Invoke a method method name formal parameters int z = max(x, y); public static int max(int num1, int num2) { actual parameters (arguments) int result; method body if (num1 > num2) result = num1; else result = num2; return result; parameter list method signature return value } 26 Formal Parameters The variables defined in the method header are known as formal parameters. Define a method modifier method header return value type Invoke a method method name formal parameters int z = max(x, y); public static int max(int num1, int num2) { actual parameters (arguments) int result; method body if (num1 > num2) result = num1; else result = num2; return result; parameter list method signature return value } 27 Actual Parameters When a method is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. Define a method modifier method header return value type Invoke a method method name formal parameters int z = max(x, y); public static int max(int num1, int num2) { actual parameters (arguments) int result; method body if (num1 > num2) result = num1; else result = num2; return result; parameter list method signature return value } 28 Passing Parameters When calling a method, the arguments must match the parameters in order, number, and compatible type public static void nPrintln(String message, int n) { for (int i = 0; i < n; i++) System.out.println(message); } public static void main(String[] args) { nPrintln(“Hello!”, 3); nPrintln(“So that’s how the methods work”, 10); } When invoking a method, the value of the argument is passed to the parameter. The variable itself is not affected. This is referred to as pass-by-value. Mechanics of the Method-Calling Process 1. Evaluate the argument expressions 2. Copy argument value into the corresponding parameter, (allocated in a newly assigned region of memory called a stack frame) 3. Execute body, using the new stack frame for local variables. 4. On a return statement, compute the return value and substitutes that value in place of the call. 5. Discard the stack frame for the method and returns to the caller, continuing where it left off. Sum Example: Call Stack public static void main(String[] args) { int i = 0; … // 1. evaluate arguments System.out.println("sum(1, 10) is: " + sum(1, 10) ); // 1+2+...+10 System.out.println("sum(25, 30) is: " + sum(25, 30) ); //25+26+...+30 System.out.println("sum(40, 50) is: " + sum(40, 50) ); //40+41+...+50 } public static int sum(int start, int end) { // 2. copy args, new SF int sum = 0; // 3. execute the body for (int i = start; i <= end; i++) { sum += i; } return sum; //4 and 5. return the value, and discard stack frame } Overloading Methods Method overloading: multiple methods can have the same name but different parameter lists Compiler determines which method is used based on the method signature (method name and parameters) – Early binding Overloading Methods public static int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } max(1, 3); max(1.0, 3.0); max(1.0, 3); Overloading Methods public static int max(int num1, int num2) { if (num1 > num2) return num1; else return num2; } public static double max(double num1, double num2) { if (num1 > num2) return num1; else return num2; } max(1, 3); max(1.0, 3.0); max(1.0, 3); Homework 1 First assignment is up and running! Next time… Arrays (passing/returning arrays to/from methods), Searching arrays (linear search, binary search) Abstract Data Types: Objects and classes Quiz 1 (bring laptop, check to make sure you are in the class on Canvas) 36