who am i
play

Who Am I? Course Introduction, Syllabus, and Course Introduction - PowerPoint PPT Presentation

Topic 1 Who Am I? Course Introduction, Syllabus, and Course Introduction Syllabus and Lecturer in CS department since 2000 Software Tools Undergrad Stanford MSCS RPI Undergrad Stanford, MSCS RPI Chapman : I didn't expect a kind of


  1. Course Materials and Procedures Course Materials and Procedures � More on assignments � Still more on assignments – some test cases provided some test cases provided – VERY IMPORTANT : must get account for CS – VERY IMPORTANT : must get account for CS department labs -> see syllabus for procedure – some provided test cases may have errors – turn in assignments to your lab account via the turnin – use class listserv to discuss and resolve errors in use class listserv to discuss and resolve errors in program – DEMO provided test cases – turn in the right thing! (source code now, jar files – create your own test cases later, correct name) later correct name) – graded on correctness, style, efficiency, – slip days, 6 total for the semester generality, comments, testing – no provisions other than slip days and “slack" in grading no provisions other than slip days and slack in grading • not graded on a linear scale or on effort t d d li l ff t scheme for late / missed assignments – program must work, compile errors / runtime – slip days and “slack” are for emergencies! errors lose all correctness points errors lose all correctness points CS307 Fundamentals of Course Overview, Materials, and Procedures CS307 Fundamentals of Course Overview, Materials, and Procedures 17 18 Computer Science Computer Science Javabat Problems Course Materials and Procedures � And yet more on assignments � Small scale problems – graded by teaching assistant and proctor graded by teaching assistant and proctor � 7 sets � 7 sets – scores posted to egradebook -> link on class web site � create account, grant access to TA / Grader – individual assignments are just that, individual – copying solution code or giving code to someone else is CHEATING -> F in the course – solutions checked with plagiarism detection software l ti h k d ith l i i d t ti ft – sharing test cases okay and encouraged – read the portion of the syllabus regarding cheating and – read the portion of the syllabus regarding cheating and collaboration CS307 Fundamentals of Course Overview, Materials, and Procedures 19 CS307 Fundamentals of Course Overview, Materials, and Procedures 20 Computer Science Computer Science

  2. Course Materials - Exams More on Exams � Out of class midterms. � old tests on line – study materials � Midterm 1: Wednesday, March 2, 6 – 8 pm y � tests consist of short answer questions and tests consist of short answer questions and � Midterm 2: Wednesday, April 20, 6 – 8 pm coding questions � test emphasize problem solving algorithm test emphasize problem solving, algorithm � If you have a conflict, relax. We will determine a implementation, some syntax makeup time. Email me ASAP. � tests scores curved up if instructor feels tests scores curved up if instructor feels necessary. � Final Exam: Uniform Time to be determined. � � registrar.utexas.edu/students/exams/ i t t d / t d t / / CS307 Fundamentals of Course Overview, Materials, and Procedures CS307 Fundamentals of Course Overview, Materials, and Procedures 21 22 Computer Science Computer Science Succeeding in the Course Succeeding in the Course � do the readings � Randy Pausch, � start on assignments early CS Professor at CMU said: � get help from the teaching staff when you get stuck � t h l f th t hi t ff h t t k on an assignment � "When I got tenure a year early at Virginia, other early at Virginia other � attend lecture and discussion sections � attend lecture and discussion sections Assistant Professors would come up to me and say, 'You � participate on the listserv got tenure early!?!?! What's your secret?!?!?' and I � do the Javabat problems do the Javabat problems would tell them, Call me in my office at 10pm on Friday uld t ll th m 'C ll m in m ffi t 10pm n F id night and I'll tell you.' " � do the extra section problems � study for tests using the old tests study for tests using the old tests � Meaning: Some things don't have an easy solution. � study for tests in groups � Some things simply require a lot of hard work. � ask questions and get help when needed as ques o s a d ge e p e eeded CS307 Fundamentals of Course Overview, Materials, and Procedures 23 CS307 Fundamentals of Course Overview, Materials, and Procedures 24 Computer Science Computer Science

  3. Course Materials and Procedures � Software – can work in CS department microlab, 5 th floor of ca o CS depa e c o ab, 5 oo o Painter Hall – login via CS account name and password g p – can work at home if you wish – Java. Java. • Free. • Web page has details under Software. ( JDK 6.0 ) – Optional IDE. • Recommended IDE is Eclipse, also free CS307 Fundamentals of Course Overview, Materials, and Procedures 25 Computer Science

  4. Agenda Topic 2 Topic 2 � Brief History of Java and overview of Java Basics language � Solve a problem to demonstrate Java syntax "On the other hand, Java has already been a big win � Discuss coding issues and style via example scuss cod g ssues a d sty e a e a p e in academic circles where it has taken the place of in academic circles, where it has taken the place of � Slides include more details on syntax Pascal as the preferred tool for teaching the basics of good programming good programming… " – may not cover everything in class, but you are may not cover everything in class but you are - The New Hacker's Dictionary version 4.3.1 expected to know these www.tuxedo.org/~esr/jargon/html/The-Jargon-Lexicon-framed.html www tuxedo org/~esr/jargon/html/The Jargon Lexicon framed html CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 1 2 Computer Science Computer Science A brief history of Java – "Java whose original name was Oak was developed as a – Java, whose original name was Oak, was developed as a part of the Green project at Sun. It was started in December '90 by Patrick Naughton, Mike Sheridan and James Gosling and was chartered to spend time trying to James Gosling and was chartered to spend time trying to figure out what would be the "next wave" of computing and Brief History of Java and how we might catch it. They came to the conclusion that at least one of the waves was going to be the convergence of least one of the waves was going to be the convergence of Overview of Langauge digitally controlled consumer devices and computers. " � Applets and Applications java.sun.com/features/1998/05/birthday.html – " The team returned to work up a Java technology-based clone of Mosaic they named "WebRunner" (after the movie Blade Runner ), later to become officially known as the HotJava TM browser It was 1994 WebRunner was just a demo but an browser. It was 1994. WebRunner was just a demo, but an impressive one: It brought to life, for the first time, animated, moving objects and dynamic executable content inside a Web browser. That had never been done. [At the TED [ conference.]" CS 307 Fundamentals of Java Basics 3 CS 307 Fundamentals of Java Basics 4 Computer Science Computer Science

  5. How Java Works More on How Java Works � Java's platform independence is achieved by the � J ' l tf i d d i hi d b th � T � To run a Java program the bytecode in a .class file J h b d i l fil use of the Java Virtual Machine is fed to an interpreter which converts the byte code � A Java program consists of one or more files with a A Java program consists of one or more files with a to machine code for a specific chip (IA 32 to machine code for a specific chip (IA-32, .java extension PowerPC) – these are plain old text files � Some people refer to the interpreter as "The Java Some people refer to the interpreter as The Java � When a Java program is compiled the .java files Virtual Machine" (JVM) are fed to a compiler which produces a .class file � The interpreter is platform specific because it takes The interpreter is platform specific because it takes for each .java file for each java file the platform independent bytecode and produces � The .class file contains Java bytecode. machine language instructions for a particular chip � Bytecode is like machine language, but it is � Bytecode is like machine language but it is � So a Java program could be run an any type of intended for the Java Virtual Machine not a specific chip such as a Pentium or PowerPC chip computer that has a JVM written for it. – PC, Mac, Unix, Linux, BeaOS, Sparc CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 5 6 Computer Science Computer Science A Picture is Worth… So What! � The platform independence of Java may be a huge The platform independence of Java may be a huge marketing tool, but is actually of little use to people The output of the learning Object Oriented Programming and compiler is .class Ab t Abstract Data Types t D t T file � What is of use is the simplicity of the Java syntax and programming concepts and programming concepts � Java is a "pure" Object Oriented Language – encapsulation, inheritance, and polymorphism encapsulation, inheritance, and polymorphism – all code must be contained in a class – no free functions (functions that do not belong to some class) like C++ altho gh someone class) like C++, although someone who wants to write ho ants to rite messy Java code certainly can The Interpreter's are sometimes referred to as the Java Virtual – Is OO the best programming paradigm? Machines CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 7 8 Computer Science Computer Science

  6. HelloWorld.java More on Java Programs � All code part of some class � All code part of some class /** public class Foo * A simple program { { //start of class Foo //start of class Foo */ /*all code in here!*/ } // end of class Foo public class HelloWorld bli l H ll W ld � The code for class Foo will be in a file { named Foo.java public static void main(String[] args) public static void main(String[] args) – just a text file with the .java extension { – a class is a programmer defined data type System.out.println( HELLO CS307! ); System.out.println("HELLO CS307!"); � A complete program will normally consist of } many different classes and thus many } } different files diff t fil CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 9 10 Computer Science Computer Science Attendance Question 1 Attendance Question 2 What does 6,967 * 7,793 equal? How many factors does 54,161,329 have? A. 10,000 A. 2 B. 23,756,201 B. 3 C 54 293 831 C. 54,293,831 C. 4 C 4 D. 2,147,483,647 D. 6 E E. - 2,147,483,648 2 14 483 648 E. more than 6 E h 6 Bonus question. What are they? CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 11 12 Computer Science Computer Science

  7. Example Problem Error Types � Determine if a given integer is prime � Syntax error / Compile errors – problem definition – caught at compile time. – really naïve algorithm – compiler did not understand or compiler does not allow – implementation � Runtime error – testing – a small improvement p – something “Bad” happens at runtime. Java breaks these into Errors and Exceptions – another improvement � Logic Error g – yet another improvement y p – program compiles and runs, but does not do – always another way ... what you intended or want – what about really big numbers? (Discover AKS what about really big numbers? (Discover AKS Primality Testing) CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 13 14 Computer Science Computer Science Basic Features � D t � Data Types T – primitives – classes / objects l / bj t Java Language � Expressions and operators � Control Structures Review of Basic Features � Arrays � Methods � Programming for correctness g g – pre and post conditions – assertions CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 15 16 Computer Science Computer Science

  8. Identifiers in Java � letters digits � letters, digits, _, and $ (don't use $. Can confuse and $ (don't use $ Can confuse the runtime system) � start with letter, , or $ , _, � by convention: 1. start with a letter Java Data Types Java Data Types 2. variables and method names, lowercase with internal 2 variables and method names lowercase with internal words capitalized e.g. honkingBigVariableName 3. constants all caps with _ between internal words e.g. ANOTHER HONKING BIG INDENTIFIER ANOTHER_HONKING_BIG_INDENTIFIER 4. classes start with capital letter, internal words capitalized, all other lowercase e.g HonkingLongClassName HonkingLongClassName � Why? To differentiate identifiers that refer to classes from those that refer to variables CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 17 18 Computer Science Computer Science Data Types Java Primitive Data Types � Primitive Data Types yp Data Data Characteristics Characteristics Range Range – byte short int long float double boolean char Type byte 8 bit signed integer -128 to 127 //dataType identifier; yp ; 16 bit signed integer -32768 to 32767 int x; short int y = 10; 32 bit signed integer -2,147,483,648 to 2,147,483,647 int int z, zz; int z zz; long 64 bit signed integer -9,223,372,036,854,775,808 to- double a = 12.0; 9,223,372,036,854,775,807 boolean done = false, prime = true; float float 32 bit floating point 32 bit floating point + 1.4E-45 to + 1 4E-45 to char mi = 'D'; number + 3.4028235E+38 double 64 bit floating point + 4.9E-324 to – stick with int for integers, double for real numbers g number + 1.7976931348623157E+308 � Classes and Objects true or false boolean NA, note Java booleans cannot be converted to or from other types – pre defined or user defined data types consisting of constructors, Unicode character, \u0000 to \uFFFF U code c a acte , \u0000 to \u char 16 bit, Unicode 16 bit, Unicode methods, and fields (constants and fields (variables) which may be methods and fields (constants and fields (variables) which may be Can mix with integer types primitives or objects.) CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 19 20 Computer Science Computer Science

  9. What are Classes and Objects? Creating and Using Objects � Class is synonymous with data type Class is synonymous with data type � Declaration - DataType identifier � D l ti D t T id tifi � Object is like a variable Rectangle r1; – The data type of the Object is some Class The data type of the Object is some Class � Creation - new operator and specified � C ti t d ifi d – referred to as an instance of a Class constructor � Classes contain: Classes contain: r1 = new Rectangle(); 1 R t l () – the implementation details of the data type Rectangle r2 = new Rectangle(); – and the interface for programmers who just want and the interface for programmers who just want � Behavior - via the dot operator � B h i i th d t t to use the data type r2.setSize(10, 20); � Objects are complex variables j p St i String s2 = r2.toString(); 2 2 t St i () – usually multiple pieces of internal data � Refer to documentation for available – various behaviors carried out via methods behaviors (methods) behaviors (methods) CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 21 22 Computer Science Computer Science Built in Classes import � import is a reserved word import is a reserved word � Java has a large built � J h l b il � S � System � packages and classes can be imported to in library of classes � Arrays another class another class with lots of useful with lots of useful � Scanner methods � does not actually import the code (unlike the � File C++ include preprocessor command) C++ include preprocessor command) � Ones you should Ones you should � Object become familiar with � statement outside the class block � Random q quickly y import java.util.ArrayList; import java util ArrayList; � Look at the Java API � String import java.awt.Rectangle; page public class Foo{ p { � Math Math // code for class Foo � Integer, Character, } Double CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 23 24 Computer Science Computer Science

  10. More on import The String Class � � can include a whole package i l d h l k � String is a standard Java class – import java.util.*; – a whole host of behaviors via methods � or list a given class � li t i l � also special (because it used so much) – import java.util.Random; – String literals exist (no other class has literals) g ( ) � i � instructs the compiler to look in the package for t t th il t l k i th k f String name = "Mike D."; types it can't find defined locally – String concatenation through the + operator � the java.lang.* package is automatically � the java lang * package is automatically String firstName = "Mike"; imported to all other classes. String lastName = "Scott"; � Not required to import classes that are part of the � Not required to import classes that are part of the String wholeName = firstName + lastName; String wholeName = firstName + lastName; same project in Eclipse – Any primitive or object on other side of + operator from a String automatically converted to String from a String automatically converted to String CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 25 26 Computer Science Computer Science Standard Output Constants � To print to standard output use � Literal constants - "the way you specify values that � Li l " h if l h are not computed and recomputed, but remain, System.out.print( expression ); // no newline well constant for the life of a program " well, constant for the life of a program. System.out.println( expression ); // newline – true, false, null, 'c', "C++", 12, -12, 12.12345 System.out.println( ); // just a newline System out println( ); // just a newline � Named constants Named constants – use the keyword final to specify a constant – scope may be local to a method or to a class scope may be local to a method or to a class common idiom is to build up expression to idi i b ild i � By convention any numerical constant besides -1, be printed out 0, 1, or 2 requires a named constant , , q final int NUM_SECTIONS = 3; System.out.println( "x is: " + x + " y is: " + y ); y p ( y y ); CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 27 28 Computer Science Computer Science

  11. Operators � Basic Assignment: � Basic Assignment: = = � Arithmetic Operators: +, -, *, /, %(remainder) – integer, floating point, and mixed arithmetic and expressions Expressions and Operators Expressions and Operators � Assignment Operators: +=, -=, *=, /=, %= � increment and decrement operators: ++, -- – prefix and postfix. – avoid use inside expressions. p int x = 3; x++; CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 29 30 Computer Science Computer Science Casting Expressions � Casting is the temporary conversion of a variable from its � Expressions are evaluated based on the � E i l t d b d th original data type to some other data type. i i l d t t t th d t t – Like being cast for a part in a play or movie precedence of operators � With primitive data types if a cast is necessary from a less p yp y � Java will automatically convert numerical � J ill t ti ll t i l inclusive data type to a more inclusive data type it is done primitive data types but results are automatically. int x = 5; sometimes surprising sometimes surprising double a = 3.5; double b = a * x + a / x; – take care when mixing integer and floating point double c = x / 2; numbers in expressions numbers in expressions � if a cast is necessary from a more inclusive to a less � if a cast is necessary from a more inclusive to a less inclusive data type the class must be done explicitly by the � The meaning of an operator is determined by programmer its operands its operands – failure to do so results in a compile error. failure to do so results in a compile error / double a = 3.5, b = 2.7; int y = (int) a / (int) b; is it integer division or floating point division? g g p y = (int)( a / b ); y = (int) a / b; //syntax error (i t) / b // t CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 31 32 Computer Science Computer Science

  12. Primitive Casting Outer ring is most inclusive data type. c us e data type double Inner ring is least inclusive. float In expressions long variables and sub expressions Java Control Structures Java Control Structures int int of less inclusive f l i l i short, data types are automatically cast char From MORE to LESS From MORE to LESS to more inclusive. to more inclusive byte If trying to place expression that is expression that is more inclusive into variable that is less inclusive, explicit cast , p must be performed. CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 33 34 Computer Science Computer Science Control Structures Boolean Expressions � linear flow of control � li fl f t l � boolean expressions evaluate to true or false � b l i l t t t f l – statements executed in consecutive order � Relational Operators: >, >=, <, <=, ==, != � Decision making with if - else statements Decision making with if - else statements � Logical Operators: &&, ||, ! if(boolean-expression) – && and || cause short circuit evaluation statement; – if the first part of p && q is false then q is not if(boolean-expression) evaluated { statement1; statement2; statement2; – if the first part of p || q is true then q is not if the first part of is true then q is not || statement3; evaluated } //example //example A single statement could be replaced by a if( x <= X_LIMIT && y <= Y_LIMIT) statement block, braces with 0 or more statements //do something inside inside CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 35 36 Computer Science Computer Science

  13. More Flow of Control for Loops � if-else: if(b if(boolean-expression) l i ) � for loops statement1; for(init-expr;boolean-expr;incr-expr) else statement; statement statement2; 2 � multiway selection: � init-expr and incr-expr can be more zero or more if(boolean-expression1) expressions or statements separated by commas expressions or statements separated by commas statement1; � statement could be replaced by a statement block else if(boolean-expression2) statement2; false false else evaluate execute skip to 1 st statement after statement3; init-expr boolean-expr body of loop � individual statements could be replaced by a statement individual statements could be replaced by a statement true true block, a set of braces with 0 or more statements execute execute � Java also has the switch statement, but not part of our body of loop incr-expr p subset subset CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 37 38 Computer Science Computer Science while loops Attendance Question 3 � hil � while loops l True or false: Strings are a primitive data while(boolean-expression) type in Java. statement; //or statement block ; // A. TRUE � do-while loop part of language do B. FALSE S statement; while(boolean-expression); � Again could use a statement block � Again, could use a statement block � break , continue , and labeled breaks – referred to in the Java tutorial as branching statements referred to in the Java tutorial as branching statements – keywords to override normal loop logic – use them judiciously (which means not much) CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 39 40 Computer Science Computer Science

  14. Attendance Question 4 What is output by the following Java code? int x = 3; double a = x / 2 + 3.5; / System.out.println(a); Arrays Arrays A. a B. 5 C. 4.5 D 4 D. 4 E. 5.0 CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 41 42 Computer Science Computer Science Arrays in Java Array Details � "Should array indices start at 0 or 1? My compromise of 0.5 was rejected � ll � all arrays must be dynamically allocated t b d i ll ll t d without, I thought, proper consideration. " – S. Kelly-Bootle � arrays have a public, final field called length � Java has built in arrays a k a native arrays Java has built in arrays. a.k.a. native arrays – built in size field, no separate variable needed � arrays hold elements of the same type – don't confuse length (capacity) with elements in – primitive data types or classes – space for array must be dynamically allocated with new operator. use (Size is any integer expression . Due to dynamic allocation does not � elements start with an index of zero, last index have to be constant.) public void arrayExamples() is length - 1 { int[] intList = new int[10]; for(int i = 0; i < intList.length; i++) � trying to access a non existent element results trying to access a non existent element results { { assert 0 > assert 0 >= i && i < intList.length; i && i < intList length; in an ArrayIndexOutOfBoundsException intList[i] = i * i * i; } ( (AIOBE) O ) intList[3] = intList[4] * intList[3]; intList[3] intList[4] intList[3]; } CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 43 44 Computer Science Computer Science

  15. Arrays of objects Array Initialization � Array variables are object variables � Array variables are object variables � A native array of objects is actually a native � A native array of objects is actually a native array of object variables � They hold the memory address of an array – all object variables in Java are really what? all object variables in Java are really what? object bj t – Pointers! � The array must be dynamically allocated public void objectArrayExamples() public void objectArrayExamples() � All values in the array are initialized (0, 0.0, { Rectangle[] rectList = new Rectangle[10]; // How many Rectangle objects exist? char 0, false, or null) rectList[5].setSize(5,10); rectList[5].setSize(5,10); //uh oh! � Arrays may be initialized with an initializer for(int i = 0; i < rectList.length; i++) list: list: { { rectList[i] new Rectangle(); rectList[i] = new Rectangle(); } int[] intList = {2, 3, 5, 7, 11, 13}; rectList[3].setSize(100,200); double[] dList = {12.12, 0.12, 45.3}; } } String[] sList = {"Olivia", "Kelly", "Isabelle"}; CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 45 46 Computer Science Computer Science The arraycopy method Array Utilities � I � In the Arrays class, static methods th l t ti th d � static void arraycopy (Object src, int srcPos, � t ti id (Obj t i t P Object dest, int destPos, int length) � binarySearch , equals , fill , and sort Copies an array from the specified source Copies an array from the specified source methods for arrays of all primitive types th d f f ll i iti t array, beginning at the specified position, to (except boolean) and arrays of Objects the specified position of the destination array. the specified position of the destination array – overloaded versions of these methods for o erloaded ersions of these methods for int[] list = new int[10]; various data types // code to fill list � In the System class there is an arraycopy In the System class there is an arraycopy // list needs to be resized method to copy elements from a specified int[] temp = new int[list.length * 2]; part of one array to another part of one array to another System.arraycopy(list, 0, temp, 0, y y py( , , p, , list.length); – can be used for arrays of primitives or arrays of list = temp; objects CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 47 48 Computer Science Computer Science

  16. 2D Arrays in Java Two Dimensional Arrays 0 1 2 3 column 0 1 2 3 column � Arrays with multiple dimensions may be declared and used 0 0 0 0 0 int[][] mat = new int[3][4]; 1 0 0 0 0 � the number of pairs of square brackets t e u be o pa s o squa e b ac ets indicates the dimension of the array. 2 0 0 0 0 � by convention in a 2D array the first number by convention, in a 2D array the first number row indicates the row and the second the column This is our abstract picture of the 2D array and treating � Java multiple dimensional arrays are � Java multiple dimensional arrays are it this way is fine. handles differently than in many other mat[2][1] = 12; programming languages programming languages. CS 307 Fundamentals of CS 307 Fundamentals of 49 50 Computer Science 2D Arrays Computer Science 2D Arrays The Real Picture Arrays of Multiple Dimension � because multiple dimensional arrays are 0 1 2 3 treated as arrays of arrays of 0 0 0 0 0 0 0 0 0 0 arrays……multiple dimensional arrays can be ragged 0 1 2 3 1 1 0 0 0 0 – each row does not have to have the same mat number of columns 0 1 2 3 2 0 0 0 0 int[][] raggedMat = new int[5][]; for(int i = 0; i < raggedMat.length; i++) mat holds the memory address of an array with 3 mat holds the memory address of an array with 3 raggedMat[i] = new int[i + 1]; d [i] i [i 1] elements. Each element holds the memory address – each row array has its own length field of an array of 4 int s of an array of 4 int s CS 307 Fundamentals of CS 307 Fundamentals of 51 52 Computer Science 2D Arrays Computer Science 2D Arrays

  17. Ragged Arrays Enhanced for loop � Ragged arrays are sometime useful, but � New in Java 5.0 � N i J 5 0 normally we deal with rectangular matrices � a.k.a. the for-each loop � useful short hand for accessing all elements in an – each row has the same number of columns as array (or other types of structures) if no need to every other row alter values alter values – use this a lot as precondition to methods that � alternative for iterating through a set of values work on matrices for(Type loop variable : set expression) for(Type loop-variable : set-expression) � working on matrices normally requires statement nested loops � logic error (not a syntax error) if try to modify an � logic error (not a syntax error) if try to modify an – why is this so hard? element in array via enhanced for loop CS 307 Fundamentals of CS 307 Fundamentals of Java Basics 53 54 Computer Science 2D Arrays Computer Science Enhanced for loop Attendance Question 5 public static int sumListOld(int[] list) p ( [] ) What is output by { int total = 0; public void d2(int x){ for(int i = 0; i < list.length; i++) the code to the right x *= 2; { { total total += list[i]; list[i]; S System.out.print(x); t t i t( ) when method d1 is System.out.println( list[i] ); } } called? return total; return total; A. 322 } public void d1(){ int x = 3; public static int sumListEnhanced(int[] list) B. 323 3 3 { int total = 0; System.out.print(x); C. 363 for(int val : list) d2(x); { total += val; D. 366 D 366 S System.out.print(x); t t i t( ) System.out.println( val ); } } E. 399 return total; } CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 55 56 Computer Science Computer Science

  18. Attendance Question 6 What is output int[] list = {5, 1, 7, 3}; by the code to System.out.print( list[2] ); System.out.print( list[4] ); S t t i t( li t[4] ) the right? A. Output will vary from one run of program to Methods Methods next B. 00 00 C. 363 D 7 then a runtime error D. 7 then a runtime error E. No output due to syntax error CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 57 58 Computer Science Computer Science Methods More on Methods � methods are analogous to procedures and functions in other languages f ti i th l � local variables can be declared within methods. � l l i bl b d l d ithi th d – local variables, parameters, instance variables – Their scope is from the point of declaration until the – must be comfortable with variable scope: where is a must be comfortable with variable scope: where is a end of the methods, unless declared inside a end of the methods unless declared inside a variable defined? smaller block like a loop � methods are the means by which objects are � methods contain statements methods contain statements manipulated (objects state is changed) - much i l t d ( bj t t t i h d) h more on this later � methods can call other methods � method header consists of method header consists of – in the same class: foo(); – in the same class: foo(); – access modifier( public , package, protected, private ) – methods to perform an operation on an object that – static keyword (optional, class method) is in scope within the method: obj.foo(); p j (); – return type (void or any data type, primitive or class) – static methods in other classes: – method name double x = Math.sqrt(1000); – parameter signature p g CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 59 60 Computer Science Computer Science

  19. static methods Method Overloading and Return � the main method is where a stand alone Java program normally begins execution ll b i ti � a class may have multiple methods with the same � l h l i l h d i h h � common compile error, trying to call a non static method name as long as the parameter signature is unique from a static one – may not overload on return type may not overload on return type public class StaticExample { public static void main(String[] args) � methods in different classes may have same name { //starting point of execution and signature and signature System.out.println("In main method"); S t t i tl ("I i th d") method1(); – this is a type of polymorphism, not method overloading method2(); //compile error; } � if a method has a return value other than void it if a method has a return value other than void it must have a return statement with a variable or public static void method1() expression of the proper type p p p yp { System.out.println( "method 1"); } � multiple return statements allowed, the first one public void method2() encountered is executed and method ends { System.out.println( "method 2"); } } – style considerations CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 61 62 Computer Science Computer Science Method Parameters Value Parameters vs. Reference Parameters R f P t � a method may have any number of parameters � A value parameter makes a copy of the A value parameter makes a copy of the � each parameter listed separately argument it is sent. � no VAR (Pascal), &, or const & (C++) o ( asca ), &, o co st & (C ) – Changes to parameter do not affect the Changes to parameter do not affect the argument. � final can be applied, but special meaning � A reference parameter is just another name A reference parameter is just another name � all parameters are pass by value � all parameters are pass by value for the argument it is sent. � Implications of pass by value??? – changes to the parameter are really changes to – changes to the parameter are really changes to the argument and thus are permanent CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 63 64 Computer Science Computer Science

  20. Value vs. Reference // C++ // C++, reference reference // // value l void add10(int& x) void add10(int x) { x += 10; } { x += 10; } void calls() void calls() { int y = 12; y Programming for Correctness Programming for Correctness { { int y 12; int y = 12; add10(y); add10(y); // y = ? // y = ? } } } } 12 12 12 12 12 y x y x CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 65 66 Computer Science Computer Science Programming by Contract Creating Correct Programs � preconditions and postconditions create a contract between preconditions and postconditions create a contract between � methods should include pre conditions and post conditions � th d h ld i l d diti d t diti the client (class or object user) and a supplier (the class or � Preconditions are things that must be true before a method object itself) is called is called – example of a contract between you and me for a test � Postconditions are things that will be true after a method is Obligations Benefits complete if the preconditions were met � it is the responsibility of the caller of a method to ensure the Client (Must ensure preconditions) (May benefit from postcondition) preconditions are met (Student) Be at test on time, bring pencil Receive fair and accurate and eraser, write legibly, evaluation of test to help formulate – the class must provide a way of ensuring the precondition is true the class must provide a way of ensuring the precondition is true answer questions in space ti i progress in course i – the preconditions must be stated in terms of the interface, not the provided implementation Supplier (Must ensure postcondition) (May assume preconditions) � it i th � it is the responsibility of the class (supplier, server) to ibilit f th l ( li ) t (Mike) (Mik ) Fairly and accurately grade F i l d t l d N No need to grade test or questions d t d t t ti test based on universal that are illegible, on wrong part of ensure the postconditions are met guidelines applied to all tests exam, or give makeup exams for unexcused absences CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 67 68 Computer Science Computer Science

  21. Thinking about pre and Precondition Example postconditions postconditions /** � pre and postconditions are part of design * Find all indices in <tt>source</tt> that are the start of a complete * match of <tt>target</tt>. * @param source != null @param source != null, source.length() > 0 source length() > 0 � coming up with pre and postconditions at the � i i h d di i h * @param target != null, target.length() > 0 * @return an ArrayList that contains the indices in source that are the time of implementation is too late * start of a complete match of target. The indices are stored in * ascending order in the ArrayList */ � the pre and post conditions drive the public static ArrayList<Integer> matches(String source, String target) { // check preconditions implementation and so must exist before the assert (source != null) && (source.length() > 0) && (target != null) && (target.length() > 0) && (target != null) && (target length() > 0) implementation can start : "matches: violation of precondition"; – The sooner you start to code, the longer your program will take. -Roy Carlson, U Wisconsin � You must spend time on design CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 69 70 Computer Science Computer Science Creating Correct Programs Assertions � Assertions have the form � A ti h th f � J � Java features has a mechanism to check the f h h i h k h correctness of your program called assertions assert boolean expression : what to output if assertion is false � A � Assertions are statements that are executed as ti t t t th t t d � Example normal statements if assertion checking is on if ( (x < 0) || (y < 0) ) { // we know either x or y is < 0 y – you should always have assertion checking on when you should always have assertion checking on when assert x < 0 || y < 0 : x + " " + y; writing and running your programs x += y; } � Assertions are boolean expressions that are p else { // we know both x and y are not less than zero evaluated when reached. If they evaluate to true assert x >= 0 && y >= 0 : x + " " + y; the program continues, if they evaluate to false y += x; } then the program halts � Use assertion liberally in your code � logical statements about the condition or state of – part of style guide your program CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 71 72 Computer Science Computer Science

  22. Assertions Uncover Errors in javadoc Your Logic Your Logic � javadoc is a program that takes the comments in Java � j d i th t t k th t i J source code and creates the html documentation pages if ( a < b ) � Open up Java source code. (Found in the src.zip file when { // we a is less than b { // we a is less than b you download the Java sdk.) assert a < b : a + " " + b; System.out.println(a + " is smaller than " + b); � Basic Format } / Summary sentence for method foo. More details. More /** Summary sentence for method foo More details More else l details. { // we know b is less than a assert b < a : a + " " + b; pre: list preconditions System.out.println(b + " is smaller than " + a); y p ( ) post: list postconditions post: list postconditions } @param x describe what x is � Use assertions in code that other @param y describe what y is @return describe what the method returns @return describe what the method returns programmers are going to use. i t */ � In the real world this is the majority of your public int foo(int x, double y) code! d ! � Comments interpreted as html CS 307 Fundamentals of Java Basics CS 307 Fundamentals of Java Basics 73 74 Computer Science Computer Science

  23. Object Variables Topic 3 References and Object Variables � object variables are declared by stating the class name / data type and then the variable name "Thou shalt not follow the NULL Thou shalt not follow the NULL – same as primitives pointer, for chaos and madness await – in Java there are hundreds of built in classes. th thee at its end." t it d " • show the API page h th API – don't learn the classes, learn how to read and use a class - Henry Spencer Henry Spencer interface (the users manual) ( ) � objects are complex variables. – They have an internal state and various behaviors that can either change the state or simply tell something about the object CS 307 Fundamentals of 1 CS 307 Fundamentals of References and Object Variables 2 Computer Science References and Object Variables Computer Science Object Variables The Pointer Sidetrack public void objectVaraiables() public void objectVaraiables() � IMPORTANT!! This material may � IMPORTANT!! This material may { Rectangle rect1; seem a bit abstract, but it is often the Rectangle rect2; cause of many a programmers logic error // 2 Rectangle objects exist?? // 2 Rectangle objects exist?? � A pointer is a variable that stores the // more code to follow memory address of where another } variable is stored a ab e s sto ed � So now there are 2 Rectangle objects right? � In some languages you can have bound variables and dynamic variables of any type � Not so much. – a bound variable is one that is associated with a b d i bl i th t i i t d ith � Object variables in Java are actually references to particular portion of memory that cannot be changed objects, not the objects themselves! � Example C++, can have an integer variable or a integer pointer (which is still a variable) i t i t ( hi h i till i bl ) – object variables store the memory address of an object of int intVar; // a int var the proper type not an object of the proper type. int * intPtr; //pointer to an int var – contrast this with primitive variables contrast this with primitive variables CS 307 Fundamentals of References and Object Variables 3 CS 307 Fundamentals of References and Object Variables 4 Computer Science Computer Science

  24. Pointer Complications Pointer Variables in C++ � C++ allows actual variables and pointers to int intVar = 5; // a int var i i 5 // i variables of any type. Things get complicated and int * intPtr; //pointer to an int var confusing very quickly intPtr = new int; int intVar = 5; // a int var i t i tV 5 // i t /* dynamically allocate an space to store an int. /* d i ll ll i int * intPtr; //pointer to an int var intPtr holds the memory address of this space*/ intPtr = new int; // allocate memory *intPtr = 12; /* assign the integer being *intPtr = 12; /* assign the integer being pointed to the value of 12. Must 5 ?? ?? ?? ?? dereference the pointer. i.e. get to 0x00122155 the thing being pointed at*/ the thing being pointed at / cout << intPtr << "\t" << *intPtr << "\t" << &intPtr << endl; space for an int in space for an int in // 3 different ways of manipulating intPtr // 3 different ways of manipulating intPtr i tV intVar i tPt intPtr memory � In C++ you can work directly with the memory assume memory address stored in intPtr address dd – increment it, assign it other memory addresses, pointer “arithmetic” 0x00122155 CS 307 Fundamentals of References and Object Variables 5 CS 307 Fundamentals of References and Object Variables 6 Computer Science Computer Science Attendance Question 1 And Now for Something Completely Different… Completely Different Given the following C++ declarations how would the variable intPtr be made to refer � Thanks Nick… to the variable intVar ? t th i bl ? � Link to Bink intVar = 5; intPtr = new int; t t e t; A. intPtr = intVar; B. intPtr = *intVar; B intPtr = *intVar; C. *intPtr = intVar; D. intPtr = &intVar; E. intPtr = intVar; CS 307 Fundamentals of References and Object Variables 7 CS 307 Fundamentals of References and Object Variables 8 Computer Science Computer Science

  25. Benefit of Pointers Time Space Trade Off � Why have pointers? Why have pointers? � Often the case that algorithms / solutions an � To allow the sharing of a variable be made faster by using more space – If several variables(objects, records, structs) need access If several variables(objects, records, structs) need access (memory) or can use less space at the to another single variable two alternatives expense of being slower. 1. keep multiple copies of variable. 2. share the data with each variable keeping a reference to BAD space the needed data used used other other ptr data data ptr p GOOD GOOD not shown not shown not shown t h shared variable shared variable time to complete time to complete sharer 2 h 2 sharer 1 CS 307 Fundamentals of References and Object Variables 9 CS 307 Fundamentals of References and Object Variables 10 Computer Science Computer Science More Benefits Dynamic Memory Allocation � Allow dynamic allocation of memory � Allow dynamic allocation of memory Your program has two chunks of memory to work – get it only when needed ( stack memory and heap with: Stack memory (or the runtime Stack ) and memory) Heap memory Heap memory � Allow linked data structures such as linked lists and binary trees When a Java program starts it receives two chunks p g – incredibly useful for certain types of problems i dibl f l f t i t f bl of memory one for the Stack and one for the Heap. � Pointers are in fact necessary in a language like Java where polymorphism is so prevalent (more on Java where polymorphism is so prevalent (more on Things that use Stack memory: local variables Things that use Stack memory: local variables, this later) parameters, and information about methods that are � Now the good news in progress. – In Java most of the complications and difficulties inherent Things that use Heap memory: everything that is with dealing with pointers are removed by some simplifications in the language simplifications in the language allocated using the new operator allocated using the new operator. CS 307 Fundamentals of References and Object Variables 11 CS 307 Fundamentals of References and Object Variables 12 Computer Science Computer Science

  26. � The Picture How Much Memory? Stack Memory Stack Memory Heap Memory Heap Memory How big is the Heap? g p String Object g j s System.out.println("Heap size is " + myChars x Runtime.getRuntime().totalMemory()); How much of the Heap is available? H e l l o y System.out.println("Available memory: " + y p ( y Runtime.getRuntime().freeMemory()); void toyCodeForMemory(int x) { int y = 10; { y ; x += y; String s = new String("Hello"); Syste .out.p System.out.println(x + " " + y + s); t ( y s); } CS 307 Fundamentals of References and Object Variables 13 CS 307 Fundamentals of References and Object Variables 14 Computer Science Computer Science References in Java Back to the Rectangle Objects � rect1 and rect2 are variables that store the memory t1 d t2 i bl th t t th � In Java all primitive variables are value addresses of Rectangle objects variables. (real, actual, direct?) right now they are uninitialized and since they are local, � right now they are uninitialized and since they are local, – it is impossible to have an integer pointer or a variables may not be used until they are given some value pointer to any variable of one of the primitive public void objectVaraiables() data types d t t { Rectangle rect1; Rectangle rect2; � All object variables are actually reference // rect1 = 0; // syntax error, C++ style // rect1 = rect2; // syntax error // rect1 = rect2; // syntax error, unitialized unitialized variables (essentially store a memory i bl ( i ll rect1 = null; // pointing at nothing address) to objects. rect2 = null; // pointing at nothing } – it is impossible to have anything but references � null is used to indicate an object variable is not pointing / to objects. You can never have a plain object naming / referring to any Rectangle object. variable i bl CS 307 Fundamentals of References and Object Variables 15 CS 307 Fundamentals of References and Object Variables 16 Computer Science Computer Science

  27. Creating Objects The Yellow Sticky Analogy � Declaring object variables does not create objects. g j j – It merely sets aside space to hold the memory address of an object. – The object must be created by using the new operator and Rectangle Object g j calling a constructor for that object x: 0 public void objectVaraiables() y: 0 { { Rectangle rect1; Rectangle rect1; rect1 t1 width: 0 rect1 = new Rectangle(); Rectangle rect2 = new Rectangle(5,10,20,30); height: 0 // (x, y, width, height) // // rect1 and rect2 now refer to Rectangle objects Rectangle Object } x: 5 x: 5 For all objects, the memory needed to store the objects, � For all objects the memory needed to store the objects is allocated dynamically using the new operator and a y: 10 constructor call. (Strings are a special case.) width: 20 rect2 rect2 – constructors are similar to methods, but they are used to constructors are similar to methods but they are used to h i ht 30 height: 30 initialize objects CS 307 Fundamentals of References and Object Variables 17 CS 307 Fundamentals of References and Object Variables 18 Computer Science Computer Science Pointers in Java Working with Objects � Is this easier? � Once an object is created and an object variable � O bj i d d bj i bl – primitives one thing, objects another? points to it then Object may be manipulated via its � can't get at the memory address the pointer stores as in C++ C++ methods methods although try this: Rectangle r1 = new Rectangle(); r1.resize(100, 200); Object obj = new Object(); r1.setLocation(10, 20); r1 setLocation(10 20); System.out.println( obj.toString() ); int area = r1.getWidth() * r1.getHeight(); � dereferencing occurs automatically Rectangle r2 = null; r2.resize( r1.getWidth(), r1.getHeight() * 2 ); ( g (), g g () ); � because of the consistency the distinction between an � because of the consistency the distinction between an // uh-oh! object and an object reference can be blurred � Use the dot operator to deference an object – "pass an object to the method" versus "pass an object reference to variable and invoke one of the objects behaviors variable and invoke one of the objects behaviors the method th th d � Need to be clear when dealing with memory address of � Available behaviors are spelled out in the class of object and when dealing with the object itself j g j the object (the data type of the object) the object, (the data type of the object) CS 307 Fundamentals of References and Object Variables 19 CS 307 Fundamentals of References and Object Variables 20 Computer Science Computer Science

  28. Attendance Question 2 What's the Output? public void objectVariables() public void objectVariables() What is output by the line of code marked { Rectangle rect1 = new Rectangle(5, 10, 15, 20); Rectangle rect2 = new Rectangle(5, 10, 15, 20);; Line 1? System.out.println("rect 1: " + rect1.toString() ); System.out.println("rect 2: " + rect2.toString() ); y p g // Line 1 A. rect1 == rect2: true System.out.println("rect1 == rect2: " + (rect1 == rect2)); rect1 = rect2; rect2.setSize(50, 100); // (newWidth, newHeight) B. rect1 == rect2: rect1 == rect2 B rect1 == rect2: rect1 == rect2 // Line 2 // Line 2 System.out.println("rect 1: " + rect1.toString() ); System.out.println("rect 2: " + rect2.toString() ); C. rect1 == rect2: false System.out.println("rect1 == rect2: " + (rect1 == rect2)); int x = 12; D. intPtr = &intVar; int y = 12; // Line 3 System.out.println("x == y: " + (x == y) ); E. rect1 == rect2: 0 x = 5; y = x; x = 10; System.out.println("x == y: " + (x == y) ); // Line 4 System.out.println("x value: " + x + ", y value: " + y); System.out.println( x value: + x + , y value: + y); } CS 307 Fundamentals of References and Object Variables 21 CS 307 Fundamentals of References and Object Variables 22 Computer Science Computer Science Attendance Question 3 Attendance Question 4 What is output by the line of code marked What will be the width and height of the Rectangle object rect1 refers to at the line of Line 3? code marked Line 2? code marked Line 2? A. x == y: 0 B x == y: 1 B. x == y: 1 A A. width = 15, height = 20 idth 15 h i ht 20 C. x == y: true B. width = 20, height = 15 D. x == y: x == y C. width = -1, height = -1 E. x == y: false D width = 0 height = 0 D. width 0, height 0 E. width = 50, height = 100 CS 307 Fundamentals of References and Object Variables 23 CS 307 Fundamentals of References and Object Variables 24 Computer Science Computer Science

  29. Attendance Question 5 Equality versus Identity A man walks into a pizza parlor, sits down, and tells A man walks into a pizza parlor sits down and tells What is output by the line of code marked the waiter, "I'll have what that lady over there is Line 4? eating." The waiter walks over to the indicated lady, picks up the pizza that is resting in front of her, and picks up the pizza that is resting in front of her and A. x value: 5, y value: 5 sets it back down in from of the man's table. � confusion over equality and identity q y y B. x value: 10, y value: 5 B x value: 10 y value: 5 � identity: two things are in fact the same thing C. x value: 0, y value: 0 � equality: two things are for all practical purposes equality: two things are for all practical purposes D. x value: 5, y value: 10; alike, but not the exact same thing E. x value: 10, y value: 10 � == versus the .equals method q – use the .equals method when you want to check the contents of the pointee, use == when you want to check memory addresses h k dd CS 307 Fundamentals of References and Object Variables 25 CS 307 Fundamentals of References and Object Variables 26 Computer Science Computer Science Just Like the Real World The Garbage Collector � Objects variables are merely names for objects � Objects variables are merely names for objects Rectangle rect1 Rectangle rect1 = new Rectangle(2,4,10,10); new Rectangle(2,4,10,10); Rectangle rect2 = new Rectangle(5,10,20,30); // (x, y, width, height) � Objects may have multiple names rect1 = rect2; /* /* what happened to the Rectangle Object what happened to the Rectangle Object – meaning there are multiple object variables rect1 was pointing at? referring to the same object (sharing) */ � If objects are allocated dynamically with new how � If objects are allocated d namicall ith ne ho Professor P f Michael! are they deallocated? Scott (Ha Ha) – delete in C++ delete in C++ � If an object becomes isolated (no longer is in Mr. Mike Mike scope), that is has no references to it, it is garbage scope), that is has no references to it, it is garbage S Scott tt and the Java Virtual Machine garbage collector will reclaim this memory AUTOMATICALLY! Daddy dd dada CS 307 Fundamentals of References and Object Variables 27 CS 307 Fundamentals of References and Object Variables 28 Computer Science Computer Science

  30. Immutable Objects Objects as Parameters � Some classes create immutable objects Some classes create immutable objects � All � All parameters in Java are value parameters t i J l t � Once created these objects cannot be changed � The method receives a copy of the parameter, – note the difference between objects and object variables note the difference between objects and object variables not the actual variable passed � Most immediate example is the String class � Makes it impossible to change a primitive p g p � String objects are immutable String objects are immutable parameter � Why might this be useful? implications for objects? (which are � implications for objects? (which are String name = "Mike"; St i "Mik " references) String sameName = name; – behavior that is similar to a reference parameter, with a p , name + name += " " + "David" + " " + "Scott"; " " + "David" + " " + "Scott"; few minor, but crucial differences System.out.println( name ); – "Reference parameter like behavior for the pointee." System out println( sameName ); System.out.println( sameName ); CS 307 Fundamentals of References and Object Variables 29 CS 307 Fundamentals of References and Object Variables 30 Computer Science Computer Science

  31. Topic 4 When Good Programs Go Bad � A variety of errors can occur when a � A E Exceptions and File I/O ti d Fil I/O i t f h program is running. For example: "A slipping gear could let your M203 A slipping gear could let your M203 – (real) user input error. bad url ( l) i t b d l – device errors. remote server unavailable grenade launcher fire when you least – physical limitations. full disk physical limitations full disk expect it. That would make you quite – code errors. interact with code that does not fulfill unpopular in what s left of your unit. unpopular in what's left of your unit " its contact (pre and post conditions) its contact (pre and post conditions) � when an error occurs - THE U.S. Army's PS magazine, August – return to safe state save work exit gracefully return to safe state, save work, exit gracefully 1993, quoted in The Java Programming � error handling code may be far removed Language, 3rd edition from code that caused the error from code that caused the error CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 1 2 Computer Science Computer Science How to Handle Errors? Exceptions � It is possible to detect and handle errors of � Many languages, including Java use a various types. mechanism know as Exceptions to handle errors at runtime � Problem: this complicates the code and – In Java Exception is a class with many makes it harder to understand. descendants. – the error detection and error handling code have – ArrayIndexOutOfBoundsException little or nothing to do with the real code is trying to do. – NullPointerException � A tradeoff between ensuring correct behavior – FileNotFoundException under all possible circumstances and clarity – ArithmeticException of the code – IllegalArgumentException CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 3 Java Basics - Exceptions and File I/O 4 Computer Science Computer Science

  32. Partial Exceptions Hierarchy Creating Exceptions Th Throwable bl � As a program runs, if a situation occurs that is handled by exceptions then an Exception Error Error E ception Exception is thrown. – An Exception object of the proper type is created IOE IOException ti R RuntimeException ti E ti – flow of control is transferred from the current block of code to code that can handle or deal with the exception ith th ti EOFException FileNotFound Exception – the normal flow of the program stops and error handling code takes over (if it exists.) handling code takes o er (if it e ists ) And many, A d many, many Arithmetic NullPointer IndexOut Illegal Exception Exception ofBounds Argument more… more Exception Exception CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 5 6 Computer Science Computer Science Attendance Question 1 Unchecked Exceptions Is it possible for the following method to � Exceptions in Java fall into two different categories – checked (other than Runtime) and unchecked (Runtime) result in an exception? � unchecked exceptions are completely preventable and u c ec ed e cept o s a e co p ete y p e e tab e a d // pre: word != null should never occur. public static void printLength(String word){ – They are caused by logic errors, created by us, the programmers. String output = "Word length is " + word.length(); � Descendents of the RuntimeException class � Descendents of the RuntimeException class System.out.println( output ); S t t i tl ( t t ) } � Examples: ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException A. Yes A. Yes � There does not need to be special error handling code B. No – just regular error prevention code � If error handling code was required programs would be e o a d g code as equ ed p og a s ou d be unwieldy because so many Java statements have the possibility of generating or causing an unchecked Exception CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 7 Java Basics - Exceptions and File I/O 8 Computer Science Computer Science

  33. Checked Exceptions Required Error Handling Code � If � If you call a method that can generate a � "Ch � "Checked exceptions represent conditions ll th d th t t k d ti t diti that, although exceptional, can reasonably checked exception you must choose how to be expected to occur and if they do occur be expected to occur, and if they do occur deal with that possible error d l ith th t ibl must be dealt with in some way.[other than � For example one class for reading from files is the program terminating.] the program terminating ]" the FileReader class – Java Programming Language third edition public FileReader (String fileName) � Unchecked exceptions are due to a Unchecked exceptions are due to a throws FileNotFoundException programming logic error, our fault and p preventable if coded correctly. y � This constructor has the possibility of throwing a p y g FileNotFoundException � Checked exceptions represent errors that � FileNotFoundException is a checked exception are unpreventable by us! p y CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 9 10 Computer Science Computer Science Checked Exceptions in Code Handling Checked Exceptions � If we have code that tries to build a FileReader we � In the code on the previous slide there are in � I th d th i lid th i must deal with the possibility of the exception fact 4 statements that can generate checked import java.io.FileReader; exceptions. exceptions public class Tester { – The FileReader constructor public int countChars(String fileName) { FileReader r = new FileReader(fileName); – the ready method the ready method int total = 0; while( r.ready() ) – the read method { r.read(); total++; – the close method – the close method } r.close(); � To deal with the exceptions we can either return total; } state this method throws an Exception of the state this method throws an Exception of the } } proper type or handle the exception within � The code contains a syntax error. "unreported exception the method itself java.io.FileNotFoundException; must be caught or declared j p ; g to be thrown." CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 11 Java Basics - Exceptions and File I/O 12 Computer Science Computer Science

  34. Using the throws Keyword Methods that throw Exceptions public int countChars(String fileName) bli i t tCh (St i fil N ) � It may be that we don't know how to deal throws FileNotFoundException, IOException with an error within the method that can { int total = 0; generate it FileReader r = new FileReader(fileName); while( r.ready() ) � In this case we will pass the buck to the { { r read(); r.read(); method that called us total++; } � The keyword throws is used to indicate a y r.close(); l () method has the possibility of generating an return total; exception of the stated type p yp } � Now any method calling ours must also � Now any method calling ours must also throw an exception or handle it throw an exception or handle it throw an exception or handle it throw an exception or handle it CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 13 14 Computer Science Computer Science Sample try and catch Blocks Using try-catch Blocks public int countChars(String fileName) { { int total = 0; int total = 0; � If you want to handle the a checked try { FileReader r = new FileReader(fileName); exception locally then use use the keywords while( r.ready() ) { { r.read(); d() try and catch d total++; } � the code that could cause an exception is r.close(); } placed in a block of code preceded by the catch(FileNotFoundException e) { System.out.println("File named " keyword try + fileName + "not found. " + e); ) total = -1; � the code that will handle the exception if it } catch(IOException e) occurs is placed in a block of code preceded p p { { System out println("IOException occured " + System.out.println( IOException occured + "while counting chars. " + e); by the keyword catch total = -1; } return total; return total; } CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 15 Java Basics - Exceptions and File I/O 16 Computer Science Computer Science

  35. Mechanics of try and catch Gacky try catch Block public int countChars3(String fileName) { { int total = 0; i t t t l 0 � Code that could cause the checked FileReader r = null; try exception is placed in a try block { r = new FileReader(fileName); } catch(FileNotFoundException e) { System.out.println("File named " + fileName + "not found. " + e); – note how the statements are included in one try block. total = -1; } try – Each statement could be in a separate try block with an { while( r.ready() ) { try associated catch block, but that is very unwieldy (see associated catch block but that is very unwieldy (see { { r.read(); r.read(); } } catch(IOException e) next slide) { System.out.println("IOException " + "occurred while counting " + "chars. " + e); � Each try block must have 1 or more Each try block must have 1 or more total = -1; } total++; associated catch blocks } } catch(IOException e) – code here to handle the error. In this case we just print code here to handle the error. In this case we just print { System.out.println("IOException occurred while counting chars. " + e); t t l total = -1;} 1 } try out the error and set result to -1 { r.close(); } catch(IOException e) { System.out.println("IOException occurred while counting chars. " + e); y p p g total = -1;} return total; } CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 17 18 Computer Science Computer Science What Happens When More try catch Mechanics Exceptions Occur Exceptions Occur � If you decide to handle the possible exception locally in a method with the try � If an exception is thrown then the normal flow of control of a program halts control of a program halts bl block you must have a corresponding catch k t h di � Instead of executing the regular statements the block Java Runtime System starts to search for a Java Runtime System starts to search for a � the catch blocks have a parameter list of 1 matching catch block � The first matching catch block based on data type � the parameter must be Exception or a p p is executed descendant of Exception � When the catch block code is completed the � Use multiple catch blocks with one try Use multiple catch blocks with one try program does not go back to where the exception program does not "go back" to where the exception block in case of multiple types of occurred. Exception s Exception s – It finds the next regular statement after the catch block g CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 19 Java Basics - Exceptions and File I/O 20 Computer Science Computer Science

  36. Counting Chars Again Throwing Exceptions Yourself � if you wish to throw an exception in your code you if you wish to throw an exception in your code you public int countChars(String fileName) public int countChars(String fileName) { int total = 0; use the throw keyword try { FileReader r = new FileReader(fileName); � Most common would be for an unmet precondition Most common would be for an unmet precondition while( r.ready() ) while( r ready() ) { r.read();// what happens in an exception occurs? total++; public class Circle } { private int iMyRadius; r.close(); (); } catch(FileNotFoundException e) /** pre: radius > 0 { System.out.println("File named " */ + fileName + "not found. " + e); public Circle(int radius) public Circle(int radius) total = -1; { if (radius <= 0) } catch(IOException e) throw new IllegalArgumentException { System.out.println("IOException occured " + ("radius must be > 0. " ( " hil "while counting chars. " + e); ti h " + ) + "Value of radius: " + radius); total = -1; iMyRadius = radius; } return total; } } } } CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 21 22 Computer Science Computer Science Attendance Question 2 Attendance Question 3 Is the use of a try-catch block on the What is output by the method badUse if it is called with the following code? previous question a proper use of try-catch int[] nums = {3, 2, 6, 1}; badUse( nums ); blocks? public static void badUse(int[] vals){ A. Yes int total = 0; try{ B. No for(int i = 0; i < vals.length; i++){ int index = vals[i]; total += vals[index]; } } catch(Exception e){ total = -1; } System.out.println(total); } A 1 A. 1 B. 0 B 0 C. 3 C 3 D. 1 D -1 E. 5 E 5 CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 23 Java Basics - Exceptions and File I/O 24 Computer Science Computer Science

  37. Error Handling, Error Handling Error Prevention Everywhere! Everywhere! � Us program logic, (ifs , fors) to prevent logic errors � U l i (if f ) t t l i and unchecked exceptions � Seems like a lot of choices for error Seems like a lot of choices for error – dereferencing a null pointer, going outside the bounds of dereferencing a null pointer, going outside the bounds of an array, violating the preconditions of a method you are prevention and error handling calling. e.g. the charAt method of the String class – normal program logic e g if’s for loop counters normal program logic, e.g. if s for loop counters – use assertions as checks on your logic use assertions as checks on your logic • you checked to ensure the variable index was within the array – assertions bounds with an if 10 lines up in the program and you are SURE – try – catch block – try – catch block you didn’t alter it. you didn t alter it. • Use an assert right before you actually access the array � When is it appropriate to use each kind? if( inbounds(index) ) { { // lots of related code // l t f l t d d // use an assertion before accessing arrayVar[index] = foo; } CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 25 26 Computer Science Computer Science Error Prevention File Input and Output � in 307 asserts can be used to check � i 307 t b d t h k � Programs must often read from and write to files � P f d f d i fil preconditions – large amounts of data – Standard Java style is to use Exceptions St d d J t l i t E ti – data not known at runtime � Use try/catch blocks on checked exceptions – data that changes over time – In general, don’t use them to handle unchecked I l d ’t th t h dl h k d � Each programming language has its own way of exceptions like NPE or AIOBE handling input and output � One place it is reasonable to use try / catch � One place it is reasonable to use try / catch – involves dealing with the operating system is in testing suites. – if possible try to hide that fact as much as possible – put each test in a try / catch. If an exception – put each test in a try / catch If an exception � J � Java attempts to standardize input and output with tt t t t d di i t d t t ith occurs that test fails, but other tests can still be the notion of a stream, an ordered sequence of run data that has a source or destination data that has a source or destination. CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 27 Java Basics - Exceptions and File I/O 28 Computer Science Computer Science

  38. Streams? Streams � A stream serves as a connection between your program and an external source or Dr Egon Spengler: Dr. Egon Spengler: Don't cross the streams Don't cross the streams. destination for bytes and bits Dr: Peter Venkman: Why not? – could be standard input or output, files, network Dr. Egon Spengler: It would be bad. connections, or other programs Dr. Peter Venkman: I'm fuzzy on the whole good/bad thing. what do you mean by "bad"? Dr. Egon Spengler: Dr. Egon Spengler: Try to imagine all life as you know it Try to imagine all life as you know it stopping instantaneously and every molecule in your body exploding at the speed of light. the speed of light Dr. Peter Venkman: That's bad. Okay. Alright, important safety tip. Thanks Egon. CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 29 30 Computer Science Computer Science Lots of Streams Working with Files in Java � Java has over sixty (60!) different stream � Data is stored in digital form, 1s and 0s � D i d i di i l f 1 d 0 types in its java.io package � Work with these in packages of 8, the byte � The IO library creates higher level abstractions so � part of the reason input and output are so we think we are working with characters, Strings, or difficult to understand in Java is the size and whole objects whole objects diversity of the IO library � Some abstract classes � The type of stream you use depends on e ype o s ea you use depe ds o – InputStream, OutputStream, Reader, and Writer InputStream OutputStream Reader and Writer what you are trying to do – InputStream and OutputStream represent the flow of data – even then there are multiple options even then there are multiple options ( (a stream) ) – Reader and Writer are used to read the data from a stream or put the data in a stream – convenience classes exist to make things a little easier CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 31 Java Basics - Exceptions and File I/O 32 Computer Science Computer Science

  39. The Scanner class Scanner and Keyboard Input � A class to make reading from source of input � No exceptions thrown! easier. New in Java 5.0 – no try – catch block necessary! � Constructors � Set delimiters with regular expressions, Scanner(InputStream) ( p ) default is whitespace Scanner(File) � Methods to read lines from input Methods to read lines from input Sca Scanner s = new Scanner(System.in); e s e Sca e (Syste . ); boolean hasNextLine() System.out.print("Enter your name: "); String nextLine() String nextLine() String name = s.nextLine(); String name s nextLine(); � Methods to read ints System.out.print("Press Enter to continue: "); int readInt(), boolean hasNext() int readInt() boolean hasNext() s.nextLine(); CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O Java Basics - Exceptions and File I/O 33 34 Computer Science Computer Science Writing to a File Hooking a Scanner up to a File //sample code to write 100 random ints to a file, 1 per line import java.util.Scanner; import java.io.PrintStream; import java.io.File; import java.io.IOException; import java.io.File; import java.io.IOException; import java.util.Random; public class ReadAndPrintScores { public class WriteToFile public static void main(String[] args) { public static void main(String[] args) { { try try { { try try { PrintStream writer = new PrintStream( new { Scanner s = new Scanner( new File("scores.dat") ); File("randInts.txt")); while( s.hasNextInt() ) Random r = new Random(); { System.out.println( s.nextInt() ); 12 35 12 final int LIMIT = 100; } } 12 45 s.close(); for(int i = 0; i < LIMIT; i++) 12 { writer.println( r.nextInt() ); } } catch(IOException e) writer.close(); 12 12 { { System out println( e ); System.out.println( e ); } } catch(IOException e) } 13 57 { System.out.println("An error occurred ” + + “while trying to write to the file"); } scores.dat } } } } CS 307 Fundamentals of CS 307 Fundamentals of Java Basics - Exceptions and File I/O 35 Java Basics - Exceptions and File I/O 36 Computer Science Computer Science

  40. Reading From a Web Page public static void main(String[] args) { public static void main(String[] args) { try { String siteUrl = "http://www.cs.utexas.edu/~scottm/cs307"); URL mySite = new URL(siteURL); y ( ); URLConnection yc = mySite.openConnection(); Scanner in = new Scanner(new InputStreamReader(yc.getInputStream())); int count = 0; while (in.hasNext()) { System.out.println(in.next()); count++; } System.out.println("Number of tokens: " + count); in.close(); } catch (Exception e) { e.printStackTrace(); p } } CS 307 Fundamentals of Java Basics - Exceptions and File I/O 37 Computer Science

  41. Topic 5 Implementing Classes Implementing Classes “And so, from Europe, we get things such , p , g g ... object-oriented analysis and design (a clever way of breaking up software Definitions Definitions programming instructions and data into small, reusable objects, based on certain abstraction principles and design b t ti i i l d d i hierarchies.)” -Michael A Cusumano -Michael A. Cusumano, The Business Of Software CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 1 2 Computer Science Computer Science Object Oriented Programming Classes Are ... � Wh � What is object oriented programming? � Another, simple definition: i bj i d i ? � "Object-oriented programming is a method of � A class is a programmer defined data type. programming based on a hierarchy of classes, and i b d hi h f l d � A data type is a set of possible values and well-defined and cooperating objects. " the operations that can be performed on t e ope at o s t at ca be pe o ed o � What is a class? � What is a class? those values � "A class is a structure that defines the data and the � Example: Example: methods to work on that data When you write methods to work on that data. When you write programs in the Java language, all program data is – single digit positive base 10 ints wrapped in a class, whether it is a class you write wrapped in a class, whether it is a class you write – 1, 2, 3, 4, 5, 6, 7, 8, 9 1 2 3 4 5 6 7 8 9 or a class you use from the Java platform API – operations: add, subtract libraries." – problems? bl ? – Sun code camp CS 307 Fundamentals of Implementing Classes 3 CS 307 Fundamentals of Implementing Classes 4 Computer Science Computer Science

  42. Data Types � Computer Languages come with built in data types � In Java, the primitive data types, native arrays A Very Short and Incomplete � Most computer languages provide a way for the ost co pute a guages p o de a ay o t e History of Object Oriented History of Object Oriented programmer to define their own data types Programming. (OOP) – Java comes with a large library of classes Java comes with a large library of classes � So object oriented programming is a way of programming that is dominated by creating new programming that is dominated by creating new data types to solve a problem. � We will look at how to create a new data type � We will look at how to create a new data type CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 5 6 Computer Science Computer Science OOP Languages OOP is not new. � Si � Simula 1 (1962 - 1965) and Simula 67 l 1 (1962 1965) d Si l 67 � Smalltalk (1970s), Alan Kay's group at Xerox (1967) Norwegian Computing Center, Oslo, PARC Norway by Ole-Johan Dahl and Kristen N b Ol J h D hl d K i t Nygaard. � C++ (early 1980s) Bjarne Stroustrup Bell � C++ (early 1980s), Bjarne Stroustrup, Bell Labs Turing Award Winners - 2001 T i A d Wi 2001 CS 307 Fundamentals of Implementing Classes 7 CS 307 Fundamentals of Implementing Classes 8 Computer Science Computer Science

  43. OOP Languages Program Design in OOP � Modula – 3, Oberon, Eiffel, Java, C#, � M d l 3 Ob Eiff l J C# � OOP breaks up problems based on the data Python types found in the problem –many languages have some Object – as opposed to breaking up the problem based on Oriented version or capability the algorithms involved � Given a problem statement, what things � One of the dominant styles for appear in the problem? implementing complex programs with p g p p g large numbers of interacting � The nouns of the problem are candidate components p classes. – … but not the only programming paradigm and � The actions and verbs of the problems are there are variations on object oriented candidate methods of the classes candidate methods of the classes programming i CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 9 10 Computer Science Computer Science Attendance Question 1 The process of taking a large problem and breaking it up into smaller parts is known as: Short Object Oriented A. Functional programming Programming Design Example B. Object oriented programming C Top down design C. Top down design D. Bottom up design E. Waterfall method E W f ll h d CS 307 Fundamentals of Implementing Classes 11 CS 307 Fundamentals of Implementing Classes 12 Computer Science Computer Science

  44. Monopoly Individual Class Design Individual Class Design If we had to start f from scratch what h h classes would we need to create? need to create? CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 13 14 Computer Science Computer Science The Steps of Class Design Class Design � Requirements Requirements � Classes should be cohesive . � Cl h ld b h i – what is the problem to be solved – They should be designed to do one thing well. – detailed requirements lead to specifications detailed requirements lead to specifications � Nouns may be classes � Verbs signal behavior and thus methods (also Verbs signal behavior and thus methods (also defines a classes responsibilities) � walkthrough scenarios to find nouns and verbs walkthrough scenarios to find nouns and verbs � Classes should be loosely coupled. � implementing and testing of classes – Changing the internal implementation details of a class � design rather than implementation is normally the design rather than implementation is normally the should not affect other classes. hardest part – loose coupling can also be achieved within a class itself – planning for reuse p g CS 307 Fundamentals of Implementing Classes 15 CS 307 Fundamentals of Implementing Classes 16 Computer Science Computer Science

  45. Encapsulation Design to Implementation � Also know as separation of concerns and � Al k i f d � Design must me implemented using the information hiding syntax of the programming language � When creating new data types (classes) the details � Wh ti d t t ( l ) th d t il � In class example with a list of integers of the actual data and the way operations work is � Slides include another example of creating a S des c ude a ot e e a p e o c eat g a hidden from the other programmers who will use hidden from the other programmers who will use class to represent a playing die those new data types – So they don't have to worry about them y y – So they can be changed without any ill effects (loose coupling) � Encapsulation makes it easier to be able to use something – microwave, radio, ipod, the Java String class i di i d th J St i l CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 17 18 Computer Science Computer Science The Problem with Arrays � Suppose I need to store a bunch of film titles � S I d t t b h f fil titl from a file The Godfather The Princess Bride A List of ints A List of ints The Incredible String[] titles = new String[100]; // I never know how much // space I need! � I want the array to grow and shrink y g CS 307 Fundamentals of Implementing Classes 19 CS 307 Fundamentals of Implementing Classes 20 Computer Science Computer Science

  46. Lists Attendance Question 2 � I need a list. When adding a new element to a list � A list is a collection of items with a definite what should be the default location to what should be the default location to order. add? � Our example will be a list of integers. Ou e a p e be a st o tege s � Design and then implement to demonstrate A. The beginning the Java syntax for creating a class the Java syntax for creating a class. B. The end C The middle C. The middle D. A random location CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 21 22 Computer Science Computer Science IntList Design Instance Variables � Internal data � I t l d t � C � Create a new, empty IntList I Li – also called instance variables because every new IntList -> [] instance (object) of this class has its own copy of instance (object) of this class has its own copy of � The above is not code. It is a notation that shows these what the results of operations. [] is an empty list. – something to store the elements of the list something to store the elements of the list � add to a list. – size of internal storage container? [].add(1) -> [1] – if not what else is needed [1].add(5) -> [1, 5] � Must be clear on the difference between the [1, 5].add(4) -> [1, 5, 4] internal data of an IntList object and the j � elements in a list have a definite order and a IntList that is being represented position. � Why make internal data private? y p – zero based position or 1 based positioning? CS 307 Fundamentals of Implementing Classes 23 CS 307 Fundamentals of Implementing Classes 24 Computer Science Computer Science

  47. Attendance Question 3 IntList aList = new IntList(); aList.add(42); aList.add(12); Our IntList class will have an instance variable aList.add(37); aList of int s ( int[] container ). What should the capacity of this internal array be? IntList Abstract view of list of integers A. less than or equal to the size of the list size 3 B. greater than or equal to the size of the list g ea e a o equa o e s e o e s [42, 12, 37] [42 12 37] container C. equal to the size of the list D. some fixed amount that never changes D some fixed amount that never changes The wall of 42 12 37 0 0 0 0 0 0 0 E. 0 abstraction. 0 1 2 3 4 5 6 7 8 9 CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 25 26 Computer Science Computer Science Constructors Default add method � For initialization of objects � where to add? � IntList constructors � what if not enough space? – default [].add(3) -> [3] – initial capacity? p y [3] add(5) -> [3 [3].add(5) > [3, 5] 5] � redirecting to another constructor [3, 5].add(3) -> [3, 5, 3] this(10); this(10); � class constants � Testing, testing, testing! – what static means what t ti means – a toString method would be useful CS 307 Fundamentals of Implementing Classes 27 CS 307 Fundamentals of Implementing Classes 28 Computer Science Computer Science

  48. toString method Attendance Question 4 � return a Java String of list What is output by the following code? � empty list -> [] IntList list = new IntList(); (); � one element -> [12] System.out.println( list.size() ); A 10 A. 10 � multiple elements -> [12 multiple elements > [12, 0, 5, 4] 0 5 4] � Beware the performance of String B. 0 concatenation. concatenation C. -1 � StringBuffer alternative D. unknown D unknown E. No output due to runtime error. CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 29 30 Computer Science Computer Science get and size methods insert method � � get t � add at someplace besides the end – access element from list [3, 5].insert(1, 4) -> [3, 4, 5] – preconditions? diti ? where what [3, 5, 2].get(0) returns 3 [3, 5, 2].get(1) returns 5 [3, 4, 5].insert(0, 4) -> [4, 3, 4, 5] � size � preconditions? � preconditions? – number of elements in the list � overload add? – Do not confuse with the capacity of the internal storage container t t i � chance for internal loose coupling – The array is not the list! [4, 5, 2].size() returns 3 () ret rns 3 [4 5 2] i CS 307 Fundamentals of Implementing Classes 31 CS 307 Fundamentals of Implementing Classes 32 Computer Science Computer Science

  49. Attendance Question 5 remove method What is output by the following code? What is output by the following code? � remove an element from the list based on IntList list = new IntList(); location list.add(3); list.insert(0, 4); [3, 4, 5].remove(0) -> [4, 5] list.insert(1, 1); [ , [3, 5, 6, 1, 2].remove(2) -> , , , ] ( ) list.add(5); ( ); list.insert(2, 9); [3, 5, 1, 2] System.out.println( list.toString() ); A [4 A. [4, 1, 3, 9, 5] � preconditions? � preconditions? 1 3 9 5] B. [3, 4, 1, 5, 9] � return value? C. [4, 1, 9, 3, 5] C. [4, 1, 9, 3, 5] – accessor methods, mutator methods, and D. [3, 1, 4, 9, 5] mutator methods that return a value E. No output due to runtime error. CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 33 34 Computer Science Computer Science Attendance Question 6 insertAll method � add all elements of one list to another What is output by the following code? starting at a specified location IntList list = new IntList(); li t list.add(12); dd(12) [5, 3, 7].insertAll(2, [2, 3]) -> list.add(15); list.add(12); [5, 3, 2, 3, 7] [ , , , , ] list.add(17); li t dd(17) list.remove(1); The parameter [2, 3] would be unchanged. System.out.println( list ); � Working with other objects of the same type � Working with other objects of the same type A. [15, 17] B. [12, 17] – this ? C [12 C. [12, 0, 12, 17] 0 12 17] – where is private private? h i i t i t ? D. [12, 12, 17] – loose coupling vs. performance E. [15, 12, 17] CS 307 Fundamentals of Implementing Classes 35 CS 307 Fundamentals of Implementing Classes 36 Computer Science Computer Science

  50. The Die Class � Consider a class used � Consider a class used to model a die � Wh t i th � What is the interface? What i t f ? Wh t Class Design and Implementation – actions should a die be able t to perform? f ? Another Example This example will not be covered in class. � The methods or behaviors can be broken up into constructors mutators accessors into constructors, mutators, accessors CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 37 38 Computer Science Computer Science The Die Class Interface Visibility Modifiers � All parts of a class have visibility modifiers � All parts of a class have visibility modifiers � Constructors (used in creation of objects) – Java keywords – default, single int parameter to specify the – public , protected, private, (no modifier means package p , p , p , ( p g number of sides, int and boolean to determine if access) should roll – do not use these modifiers on local variables (syntax error) � public means that constructor, method, or field may � public means that constructor method or field may � Mutators (change state of objects) � ( f ) be accessed outside of the class. – roll – part of the interface pa o e e ace � Accessors (do not change state of objects) – constructors and methods are generally public � private means that part of the class is hidden and – getResult, getNumSides, toString g , g , g inaccessible by code outside of the class � Public constants – part of the implementation – DEFAULT SIDES DEFAULT_SIDES – data fields are generally private data fields are generally private CS 307 Fundamentals of Implementing Classes 39 CS 307 Fundamentals of Implementing Classes 40 Computer Science Computer Science

  51. The Die Class Implementation DieTester method � Implementation is made up of constructor code, p p , method code, and private data members of the class. public static void main(String[] args) { � scope of data members / instance variables � scope of data members / instance variables final int NUM ROLLS = 50; final int NUM_ROLLS 50; final int TEN_SIDED = 10; – private data members may be used in any of the Die d1 = new Die(); Die d2 = new Die(); constructors or methods of a class Die d3 = new Die(TEN SIDED); _ � Implementation is hidden from users of a class and � I l t ti i hidd f f l d final int MAX_ROLL = d1.getNumSides() + d2.getNumSides() + d3.getNumSides(); can be changed without changing the interface or affecting clients (other classes that use this class) affecting clients (other classes that use this class) for(int i = 0; i < NUM_ROLLS; i++) – Example: Previous version of Die class, { d1.roll(); DieVersion1.java d2.roll(); System.out.println("d1: " + d1.getResult() � Once Die class completed can be used in anything Once Die class completed can be used in anything + " d2 + " d2: " + d2.getResult() + " Total: " " + d2 tR lt() + " T t l " requiring a Die or situation requiring random + (d1.getResult() + d2.getResult() ) ); } numbers between 1 and N – DieTester class. What does it do? Di T t l Wh t d it d ? CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 41 42 Computer Science Computer Science DieTester continued Correctness Sidetrack � Wh � When creating the public interface of a class give ti th bli i t f f l i int total = 0; careful thought and consideration to the contract int numRolls = 0; do you a e c ea you are creating between yourself and users (other g be ee you se a d use s (o e { { d1 d1.roll(); ll() programmers) of your class d2.roll(); d3.roll(); � Use preconditions to state what you assume to be total = d1.getResult() + d2.getResult() + d3 getResult(); + d3.getResult(); true before a method is called f numRolls++; } – caller of the method is responsible for making sure these while(total != MAX_ROLL); are true are true System.out.println("\n\nNumber of rolls to get " � Use post conditions to state what you guarantee to + MAX_ROLL + " was " + numRolls); be true after the method is done if the preconditions are met – implementer of the method is responsible for making sure these are true sure these are true CS 307 Fundamentals of Implementing Classes 43 CS 307 Fundamentals of Implementing Classes 44 Computer Science Computer Science

  52. Object Behavior - Instantiation Precondition and Postcondition Example P t diti E l � Consider the DieTester class � C id h Di T l Die d1 = new Die(); /* pre: numSides > 1 Die d2 new Die(); Die d2 = new Die(); post: getResult() = 1, getNumSides() = sides Die d3 = new Die(10); */ � When the new operator is invoked control is p public Die(int numSides) bli Di (i t Sid ) transferred to the Die class and the specified { assert (numSides > 1) : “Violation of precondition: Die(int)”; constructor is executed, based on parameter matching iMyNumSides = numSides; iMyNumSides = numSides; � Space(memory) is set aside for the new object's fields iMyResult = 1; � The memory address of the new object is passed assert getResult() assert getResult() == 1 && getNumSides() == numSides; 1 && getNumSides() numSides; back and stored in the object variable (pointer) } � After creating the object, methods may be called on it. CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 45 46 Computer Science Computer Science Creating Dice Objects Objects � Every Die object created has its own � E Di bj t t d h it memory a Die object address instance of the variables declared in the 6 1 class blueprint class blueprint d1 d1 DieTester class. Sees iMySides iMyResult private int iMySides; Die class. interface of Die class Sees private int iMyResult; private int iMyResult; a Die object a Die object implementation. � thus the term instance variable memory (of Die class.) 6 1 � the instance vars are part of the hidden � the instance vars are part of the hidden address address iMySides iMyResult implementation and may be of any data type d2 a Die object j – unless they are public which is almost always a – unless they are public, which is almost always a memory bad idea if you follow the tenets of information 10 1 address hiding and encapsulation d3 iMySides iMyResult CS 307 Fundamentals of Implementing Classes 47 CS 307 Fundamentals of Implementing Classes 48 Computer Science Computer Science

  53. Complex Objects The Implicit Parameter � What if one of the instance variables is itself � Consider this code from the Die class � Consider this code from the Die class an object? public void roll() � add to the Die class { iMyResult = add to the Die class ourRandomNumGen.nextInt(iMySides) + 1; private String myName; } � Taken in isolation this code is rather confusing. Taken in isolation this code is rather confusing. a Die object a Die object memory � what is this iMyResult thing? address memory 6 1 address – It's not a parameter or local variable p d1 d1 iMySides iMyResult myName – why does it exist? – it belongs to the Die object that called this method d1 can hold the memory address d1 can hold the memory address a String object of a Die object. The instance variable – if there are numerous Die objects in existence myName inside a Die object can hold – Which one is used depends on which object called implementation the memory address of a String object the memory address of a String object details not shown details not shown the method the method. CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 49 50 Computer Science Computer Science this Visually The this Keyword memory // in some class other than Die // i l th th Di address dd � When a method is called it may be necessary Die d3 = new Die(); d3 for the calling object to be able to refer to itself d3.roll(); – most likely so it can pass itself somewhere as a // in the Die class parameter public void roll() { { iMyResult = iMyResult = � when an object calls a method an implicit � hen an object calls a method an implicit ourRandomNumGen.nextInt(iMySides) + 1; reference is assigned to the calling object /* OR � the name of this implicit reference is this � the name of this implicit reference is this thi this.iMyResult… iM R lt a Die object */ � this is a reference to the current calling object memory } and may be used as an object variable (may not and may be used as an object variable (may not 6 6 1 1 address declare it) this iMySides iMyResult CS 307 Fundamentals of Implementing Classes 51 CS 307 Fundamentals of Implementing Classes 52 Computer Science Computer Science

  54. A Possible Equals Method An equals method q p public boolean equals(Object otherObject) q j j { Die other = (Die)otherObject; return iMySides == other.iMySides � working with objects of the same type in a working with objects of the same type in a && iMyResult== other iMyResult && iMyResult== other.iMyResult class can be confusing && myName.equals( other.myName ); } � write an equals method for the Die class write an equals method for the Die class. � Declared Type of Parameter is Object not Die � Declared Type of Parameter is Object not Die assume every Die has a myName instance � override (replace) the equals method instead of overload (present an alternate version) overload (present an alternate version) variable as well as iMyNumber and iMySides variable as well as iMyNumber and iMySides – easier to create generic code � we will see the equals method is inherited from the Object class � access to another object's private instance variables? variables? CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 53 54 Computer Science Computer Science Another equals Methods A "Perfect" Equals Method � From Cay Horstmann's Core Java public boolean equals(Object otherObject) public boolean equals(Object otherObject) { Die other = (Die)otherObject; { { // check if objects identical // check if objects identical return this.iMySides == other.iMySides if( this == otherObject) && this.iMyNumber == other.iMyNumber return true; && this.myName.equals( other.myName ); y q ( y ); // // must return false if explicit parameter null ust etu a se e p c t pa a ete u } if(otherObject == null) return false; // if objects not of same type they cannot be equal if(getClass() != otherObject.getClass() ) Using the this keyword / reference to access the implicit parameters return false; instance variables is unnecessary. // we know otherObject is a non null Die If If a method within the same class is called within a method, the th d ithi th l i ll d ithi th d th Die other = (Die)otherObject; return iMySides == other.iMySides original calling object is still the calling object && iMyNumber == other.iMyNumber && m Name eq als( other m Name ) && myName.equals( other.myName ); } CS 307 Fundamentals of Implementing Classes 55 CS 307 Fundamentals of Implementing Classes 56 Computer Science Computer Science

  55. the instanceof Operator Class Variables and Class Methods � instanceof is a Java keyword. � i J k d � Sometimes every object of a class does not � part of a boolean statement need its own copy of a variable or constant need its own copy of a variable or constant public boolean equals(Object otherObj) � The keyword static is used to specify { if otherObj instanceof Die class variables, constants, and methods class variables, constants, and methods { //now go and cast private static Random ourRandNumGen // rest of equals method = new Random(); public static final int DEFAULT_SIDES = 6; public static final int DEFAULT SIDES = 6; } � The most prevalent use of static is for class } constants. constants � Should not use instanceof in equals methods. � Should not use instanceof in equals methods – if the value can't be changed why should every � instanceof has its uses but not in equals object have a copy of this non changing value j py g g because of the contract of the equals method b f th t t f th l th d CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 57 58 Computer Science Computer Science Syntax for Accessing Class Variables Class Variables and Constants public class UseDieStatic public class UseDieStatic { public static void main(String[] args) the Die class { System.out.println( "Die.DEFAULT_SIDES " + Die.DEFAULT_SIDES ); memory // // Any attempt to access Die.ourRandNumGen 6 address // would generate a syntax error DEFAULT_SIDES ourRandNumGen Die d1 = new Die(10); ( ); a Random object System.out.println( "Die.DEFAULT_SIDES " All objects of type Die have + Die.DEFAULT_SIDES ); implementation implementation access to the class variables t th l i bl S System.out.println( "d1.DEFAULT_SIDES " t t i tl ( "d1 DEFAULT SIDES " details not shown + d1.DEFAULT_SIDES ); and constants. // regardless of the number of Die objects in A public class variable or constant // existence, there is only one copy of DEFAULT_SIDES // in the Die class may be referred to via the class name. } // end of main method } // end of main method } // end of UseDieStatic class CS 307 Fundamentals of Implementing Classes 59 CS 307 Fundamentals of Implementing Classes 60 Computer Science Computer Science

  56. Static Methods Static Methods Continued � static has a somewhat different � Since there is no implicit object parameter meaning when used in a method sent to the static method it does not have d declaration l ti access to a copy of any objects instance � static methods may not manipulate any variables instance variables i t i bl – unless of course that object is sent as an l f th t bj t i t explicit parameter � in non static methods, some object � Static methods are normally utility methods � Static methods are normally utility methods invokes the method i k th th d or used to manipulate static variables d3.roll(); ( class variables ) ( class variables ) � the object that makes the method call is � The Math and System classes are nothing an implicit parameter to the method but static methods but static methods CS 307 Fundamentals of Implementing Classes CS 307 Fundamentals of Implementing Classes 61 62 Computer Science Computer Science static and this � Why does this work (added to Die class) Why does this work (added to Die class) public class Die { public void outputSelf() { System.out.println( this ); } } } � but this doesn't? but this doesn t? public class StaticThis { public static void main(String[] args) public static void main(String[] args) { System.out.println( this ); } } } CS 307 Fundamentals of Implementing Classes 63 Computer Science

  57. Outline Topic 6 Topic 6 � Explanation of inheritance. � Using inheritance to create a SortedIntList. Inheritance and Inheritance and � Explanation of polymorphism. Polymorphism � Using polymorphism to make a more generic Using polymorphism to make a more generic "Question: What is the object oriented way of List class. getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.” CS 307 Fundamentals of CS 307 Fundamentals of 1 2 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism Main Tenets of OO Programming � Encapsulation – abstraction, information hiding abs ac o , o a o d g � Inheritance Explanation of Inheritance Explanation of Inheritance – code reuse, specialization New code using old code reuse specialization "New code using old code." � Polymorphism � Polymorphism – do X for a collection of various types of objects, where X is different depending on the type of where X is different depending on the type of object – "Old code using new code " Old code using new code. CS 307 Fundamentals of 3 CS 307 Fundamentals of 4 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  58. Things and Relationships The “has-A” Relationship � Object oriented programming leads to � Obj t i t d i l d t � Objects are often made up of many parts or programs that are models have sub data. – sometimes models of things in the real world ti d l f thi i th l ld – chess piece: position, color – sometimes models of contrived or imaginary things – die: result, number of sides � There are many types of relationships between � There are many types of relationships between � This “has-a” relationship is modeled by the things in the models composition p – chess piece has a position chess piece has a position – the instance variables or fields internal to objects – chess piece has a color � Encapsulation captures this concept Encapsulation captures this concept – chess piece moves (changes position) chess piece moves (changes position) – chess piece is taken – a rook is a type of chess piece a rook is a type of chess piece CS 307 Fundamentals of CS 307 Fundamentals of 5 6 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism The “is-a” relationship Inheritance � Another type of relationship found in the real � The “is-a” relationship, and the specialization world that accompanies it, is modeled in object oriented languages via inheritance – a rook is a chess piece � Classes can inherit from other classes – a queen is a chess piece – a student is a person – base inheritance in a program on the real world things being modeled – a faculty member is a person – does “an A is a B” make sense? Is it logical? – an undergraduate student is a student � “is-a” usually denotes some form of is a usually denotes some form of specialization � it is not the same as “has-a” it is not the same as has-a CS 307 Fundamentals of 7 CS 307 Fundamentals of 8 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  59. Nomenclature of Inheritance Results of Inheritance � In Java the extends keyword is used in the � I J th k d i d i th t d public class A class header to specify which preexisting class public class B extends A a new class is inheriting from a e c ass s e g o � the sub class inherits (gains) all instance public class Student extends Person � Person is said to be variables and instance methods of the super a ab es a d sta ce et ods o t e supe – the parent class of Student h l f S d class, automatically – the super class of Student – the base class of Student � additional methods can be added to class B additional methods can be added to class B – an ancestor of Student (specialization) � Student is said to be – a child class of Person � the sub class can replace (redefine, � the sub class can replace (redefine – a sub class of Person override) methods from the super class – a derived class of Person – a descendant of Person CS 307 Fundamentals of CS 307 Fundamentals of 9 10 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism Inheritance in Java Attendance Question 1 � Java is a pure object oriented language Java is a pure object oriented language What is the primary reason for using � all code is part of some class inheritance when programming? � all classes, except one, must inherit from � all classes except one must inherit from exactly one other class A. To make a program more complicated � The Object class is the cosmic super class The Object class is the cosmic super class B. To duplicate code between classes – The Object class does not inherit from any other class – The Object class has several important methods: C. To reuse pre-existing code C To reuse pre-existing code toString , equals , hashCode , clone , getClass D. To hide implementation details of a class � implications: – all classes are descendants of Object all classes are descendants of Object E. To ensure pre conditions of methods are met. – all classes and thus all objects have a toString , equals , hashCode , clone , and getClass method • toString , equals , hashCode , clone normally overridden CS 307 Fundamentals of 11 CS 307 Fundamentals of 12 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  60. Overriding methods Inheritance in Java � If a class header does not include the � If l h d d t i l d th � any method that is not final may be extends clause the class extends the overridden by a descendant class y Object class by default t class by default Obj � same signature as method in ancestor public class Die � may not reduce visibility � may not reduce visibility – Object is an ancestor to all classes i ll l � may use the original method if simply want to – it is the only class that does not extend some add more behavior to existing dd b h i t i ti other class th l � A class extends exactly one other class – extending two or more classes is multiple inheritance. Java does not support this directly, rather it uses Interfaces . th it I t f CS 307 Fundamentals of CS 307 Fundamentals of 13 14 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism Attendance Question 2 Shape Classes � Declare a class called ClosedShape � D l l ll d What is output when the main method is run? public class Foo{ – assume all shapes have x and y coordinates public static void main(String[] args){ Foo f1 = new Foo(); – override Object 's version of toString System.out.println( f1.toString() ); } � Possible sub classes of ClosedShape } – Rectangle A. 0 – Circle B. null B null – Ellipse C. Unknown until code is actually run. – Square Square D. No output due to a syntax error. � Possible hierarchy E. No output due to a runtime error. p ClosedShape < Rectangle < Square ClosedShape <- Rectangle <- Square CS 307 Fundamentals of 15 CS 307 Fundamentals of 16 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  61. A ClosedShape class Constructors p public class ClosedShape p � Constructors handle initialization of objects � Constructors handle initialization of objects { private double myX; private double myY; � When creating an object with one or more ancestors (every type except Object) a chain of constructor calls takes place yp p j ) p public ClosedShape() public ClosedShape() { this(0,0); } � The reserved word super may be used in a constructor to call a one of the parent's constructors public ClosedShape (double x, double y) { myX = x; { myX x; – must be first line of constructor t b fi t li f t t myY = y; � if no parent constructor is explicitly called the default, 0 } p parameter constructor of the parent is called p public String toString() bli i i () – if no default constructor exists a syntax error results { return "x: " + getX() + " y: " + getY(); } � If a parent constructor is called another constructor in the public double getX(){ return myX; } p g y same class may no be called same class ma no be called public double getY(){ return myY; } } – no super();this(); allowed. One or the other, not both // Other methods not shown – good place for an initialization method CS 307 Fundamentals of CS 307 Fundamentals of 17 18 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism A Rectangle Class A Rectangle Constructor public class Rectangle extends ClosedShape { private double myWidth; public class Rectangle extends ClosedShape private double myHeight; { private double myWidth; public Rectangle() private double myHeight; { this(0, 0); { this(0 0); } public Rectangle( double x, double y, public Rectangle(double width, double height) double width, double height ) g { myWidth = width; myHeight = height; { super(x,y); } // calls the 2 double constructor in public Rectangle(double x, double y, // ClosedShape p double width, double height) double width double height) myWidth = width; { super(x, y); myWidth = width; myHeight = height; myHeight = height; } } public String toString() { return super.toString() + " width " + myWidth + " height " + myHeight; // other methods not shown } } } } CS 307 Fundamentals of 19 CS 307 Fundamentals of 20 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  62. Initialization method The Keyword super public class Rectangle extends ClosedShape public class Rectangle extends ClosedShape � super is used to access something (any protected or { private double myWidth; private double myHeight; public field or method) from the super class that has been overridden been overridden public Rectangle() public Rectangle() { init(0, 0); � Rectangle's toString makes use of the toString in } ClosedShape my calling super.toString() public Rectangle(double width, double height) public Rectangle(double width, double height) � without the super calling toString would result in { init(width, height); } infinite recursive calls public Rectangle(double x, double y, public Rectangle(double x double y � J � Java does not allow nested supers d t ll t d double width, double height) super.super.toString() { super(x, y); init(width, height); results in a syntax error even though technically this results in a syntax error even though technically this } refers to a valid method, Object 's toString private void init(double width, double height) � Rectangle partially overrides ClosedShapes toString { myWidth = width; myHeight = height; myHeight = height; } CS 307 Fundamentals of CS 307 Fundamentals of 21 22 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism The Real Picture Result of Inheritance Do an of these ca se a s nta error? Do any of these cause a syntax error? Fields from Object class Fields from Object class What is the output? Instance variables declared in Object declared in Object Rectangle r = new Rectangle(1, 2, 3, 4); Fields from ClosedShape class ClosedShape s = new CloseShape(2, 3); p p , A A System.out.println( s.getX() ); Rectangle Instance Variables declared in System.out.println( s.getY() ); object ClosedShape p System.out.println( s.toString() ); System out println( s toString() ); System.out.println( r.getX() ); Available Fields from Rectangle class System.out.println( r.getY() ); y p ( g () ) methods are all methods System.out.println( r.toString() ); Instance Variables declared in from Object, System.out.println( r.getWidth() ); ClosedShape, Rectangle and Rectangle and Rectangle CS 307 Fundamentals of 23 CS 307 Fundamentals of 24 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  63. Access Modifiers and Why private Vars and not protected? Inheritance Inheritance � public � In general it is good practice to make – accessible to all classes accessible to all classes instance variables private instance variables private � private – hide them from your descendants – accessible only within that class. Hidden from all sub y – if you think descendants will need to access if thi k d d t ill d t classes. them or modify them provide protected methods � protected to do this to do this – accessible by classes within the same package and all ibl b l ithi th k d ll descendant classes � Why? � Instance variables should be private p � Consider the following example � protected methods are used to allow descendant classes to modify instance variables in ways other classes can't l 't CS 307 Fundamentals of CS 307 Fundamentals of 25 26 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism Required update public class GamePiece { private Board myBoard; private Position myPos; private Position myPos; Creating a SortedIntList Creating a SortedIntList // whenever my position changes I must y p g // update the board so it knows about the change protected void alterPos( Position newPos ) { Position oldPos = myPos; myPos = newPos; myPos newPos; myBoard.update( oldPos, myPos ); } CS 307 Fundamentals of 27 CS 307 Fundamentals of 28 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  64. Implementing SortedIntList A New Class � Assume we want to have a list of ints, but � Do we have to write a whole new class? that the ints must always be maintained in � Assume we have an IntList class. ascending order � Which of the following methods would have [-7, 12, 37, 212, 212, 313, 313, 500] to be c a ged to be changed? sortedList.get(0) returns the min add(int value) sortedList.get( list.size() – 1 ) int get(int location) int get(int location) returns the max String toString() int size() int size() int remove(int location) CS 307 Fundamentals of CS 307 Fundamentals of 29 30 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism Overriding the add Method Problems � First attempt � What about this method? � Problem? void insert(int location, int val) � solving with protected � What about this method? – What protected really means What protected really means void insertAll(int location, void insertAll(int location IntList otherList) � solving with insert method � SortedIntList is not the cleanest � SortedIntList is not the cleanest – double edged sort double edged sort application of inheritance. CS 307 Fundamentals of 31 CS 307 Fundamentals of 32 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  65. Polymorphism � A � Another feature of OOP th f t f OOP � literally “having many forms” � object variables in Java are polymorphic � object variables can refer to objects or their Explanation of Polymorphism Explanation of Polymorphism declared type AND any objects that are descendants of the declared type ClosedShape s = new ClosedShape(); s = new Rectangle(); // legal! R t l () // l l! s = new Circle(); //legal! Obj Object obj1; // = what? t bj1 // h t? CS 307 Fundamentals of CS 307 Fundamentals of 33 34 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism Data Type Attendance Question 3 � bj � object variables have: t i bl h Consider the following class declarations: – a declared type . Also called the static type. public class BoardSpace public class Property extends BoardSpace public class Property extends BoardSpace – a dynamic type . What is the actual type of the d i t Wh t i th t l t f th public class Street extends Property pointee at run time or when a particular public class Railroad extends Property statement is executed. statement is executed. Which of the following statements would cause a syntax Which of the following statements would cause a syntax � Method calls are syntactically legal if the error? Assume all classes have a default constructor. A. Object obj = new Railroad(); method is in the declared type or any e od s e dec a ed ype o a y ancestor of the declared type B. Street s = new BoardSpace(); C. BoardSpace b = new Street(); � The actual method that is executed at D. Railroad r = new Street(); runtime is based on the dynamic type E. More than one of these – dynamic dispatch y p CS 307 Fundamentals of 35 CS 307 Fundamentals of 36 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  66. What’s the Output? Method LookUp ClosedShape s = new ClosedShape(1,2); � To determine if a method is legal the compiler looks in the class based on the declared type System.out.println( s.toString() ); – if it finds it great, if not go to the super class and look there if it finds it great, if not go to the super class and look there s = new Rectangle(2, 3, 4, 5); s ne Rectangle(2 3 4 5) – continue until the method is found, or the Object class is reached System.out.println( s.toString() ); and the method was never found. (Compile error) s new Circle(4, 5, 10); s = new Circle(4, 5, 10); � To determine which method is actually executed the run To determine which method is actually executed the run time system System.out.println( s.toString() ); – starts with the actual run time class of the object that is calling the s = new ClosedShape(); method method System.out.println( s.toString() ); – search the class for that method – if found, execute it, otherwise go to the super class and keep looking – repeat until a version is found repeat until a version is found � Is it possible the runtime system won’t find a method? CS 307 Fundamentals of CS 307 Fundamentals of 37 38 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism Attendance Question 4 Why Bother? What is output by the What is output by the � Inheritance allows programs to model � I h it ll t d l public class Animal{ code to the right when public String bt(){ return "!"; } relationships in the real world } run? – if the program follows the model it may be easier if th f ll th d l it b i A. !!live public class Mammal extends Animal{ to write public String bt(){ return "live"; } B. !eggegg gg gg } � Inheritance allows code reuse � Inheritance allows code reuse C. !egglive public class Platypus extends Mammal{ – complete programs faster (especially large public String bt(){ return "egg";} D. !!! D !!! programs) programs) } } � Polymorphism allows code reuse in another E. eggegglive Animal a1 = new Animal(); way (We will explore this next time) y ( p ) Animal a2 = new Platypus(); Mammal m1 = new Platypus(); � Inheritance and polymorphism allow System.out.print( a1.bt() ); System.out.print( a2.bt() ); programmers to create generic algorithms p g g g System.out.print( m1.bt() ); CS 307 Fundamentals of 39 CS 307 Fundamentals of 40 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  67. Genericity the createASet example � One of the goals of OOP is the support of � O f th l f OOP i th t f public Object[] createASet(Object[] items) code reuse to allow more efficient program { /* development development pre: items != null, no elements � If a algorithm is essentially the same, but the of items = null code would vary based on the data type code would vary based on the data type post: return an array of Objects post: return an array of Objects that represents a set of the elements genericity allows only a single version of that in items. (all duplicates removed) code to exist code to exist */ / – some languages support genericity via templates – in Java, there are 2 ways of doing this in Java, there are 2 ways of doing this • polymorphism and the inheritance requirement {5, 1, 2, 3, 2, 3, 1, 5} -> {5, 1, 2, 3} • generics CS 307 Fundamentals of CS 307 Fundamentals of 41 42 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism createASet examples String[] sList = {"Texas", "texas", "Texas", "Texas", "UT", "texas"}; Object[] sSet = createASet(sList); for(int i = 0; i < sSet.length; i++) System.out.println( sSet[i] ); A Generic List Class A Generic List Class Object[] list = {"Hi", 1, 4, 3.3, true, new ArrayList(), "Hi", 3.3, 4}; Object[] set Object[] set = createASet(list); createASet(list); for(int i = 0; i < set.length; i++) System.out.println( set[i] ); CS 307 Fundamentals of 43 CS 307 Fundamentals of 44 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  68. Back to IntList Generic List Class � We may find IntList useful, but what if we � W fi d f l b t h t if � required changes want a List of String s? Rectangle s? � How does toString have to change? List s? ? – why?!?! – What if I am not sure? – A good example of why keyword this is g p y y � Are the List algorithms going to be very necessary from toString different if I am storing String s instead of � What can a List hold now? int s? � How many List classes do I need? � How can we make a generic List class? How can we make a generic List class? CS 307 Fundamentals of CS 307 Fundamentals of 45 46 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism Writing an equals Method equals method � How to check if two objects are equal? � read the javadoc carefully! � don't rely on toString and String 's equal if(objA == objA) // does this work? � lost of cases � Why not this Why not this public boolean equals(List other) � B � Because public void foo(List a, Object b) if( a.equals(b) ) System.out.println( same ) – what if b is really a List ? CS 307 Fundamentals of 47 CS 307 Fundamentals of 48 Computer Science Inheritance and Polymorphism Computer Science Inheritance and Polymorphism

  69. T Topic 7 i 7 Interfaces and Abstract Interfaces and Abstract Classes Interfaces Interfaces “I prefer Agassiz in the abstract, rather than in the concrete.” CS 307 Fundamentals of CS 307 Fundamentals of 1 2 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes Multiple Inheritance Problems with Multiple Inheritance � Suppose multiple inheritance was allowed � S lti l i h it ll d � The are classes where the “is-a” test is true public class GradTA extends Faculty, GradStudent for more than one other class � Suppose Faculty overrides toString and that � Suppose Faculty overrides toString and that – a graduate teaching assistant is a graduate GradStudent overrides toString as well students GradTA ta1 = new GradTA(); GradTA ta1 = new GradTA(); – a graduate teaching assistant is a faculty System.out.println( ta1.toString() ); member � What is the problem What is the problem � Java requires all classes to inherit from � Certainly possible to overcome the problem exactly one other class – provide access to both (scope resolution in C++) – provide access to both (scope resolution in C++) – does not allow multiple inheritance – require GradTA to pick a version of toString or – some object oriented languages do override it itself (Eiffel) ( ) CS 307 Fundamentals of 3 CS 307 Fundamentals of 4 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes

  70. A List Interface Interfaces – Not quite Multiple Inheritance � Java does not allow multiple inheritance � What if we wanted to specify the operations for a List, but no implementation? – syntax headaches not worth the benefits � Allow for multiple, different implementations. � Java has a mechanism to allow specification of a data type with NO implementation yp p � Provides a way of creating abstractions. o des a ay o c eat g abst act o s – interfaces – a central idea of computer science and programming. p g g � Pure Design Pure Design – specify "what" without specifying "how" – allow a form of multiple inheritance without the possibility of conflicting implementations possibility of conflicting implementations – "Abstraction is a mechanism and practice to Abstraction is a mechanism and practice to reduce and factor out details so that one can focus on a few concepts at a time. " CS 307 Fundamentals of CS 307 Fundamentals of 5 6 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes Interface Syntax Interfaces public interface List{ i i i � All methods in interfaces are public and public void add(Object val); abstract public int size(); – can leave off those modifiers in method headers public Object get(int location); � No constructors public void insert(int location, � No instance variables Object val); � can have class constants � can have class constants public void addAll(List other); public static final int DEFAULT_SIDES = 6 public Object remove(int location); } CS 307 Fundamentals of 7 CS 307 Fundamentals of 8 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes

  71. Implementing Interfaces Why interfaces? � A class inherits (extends) exactly one other � I � Interfaces allow the creation of abstract data types f ll h i f b t t d t t class, but … – "A set of data values and associated operations that are precisely specified independent of any particular precisely specified independent of any particular � A class can implement as many interfaces implementation. " as it likes – multiple implementations allowed � Interfaces allow a class to be specified without public class ArrayList implements List worrying about the implementation � A class that implements an interface must A class that implements an interface must – do design first provide implementations of all method – What will this data type do? declared in the interface or the class must be declared in the interface or the class must be – Don’t worry about implementation until design is done. D ’t b t i l t ti til d i i d abstract – separation of concerns � interfaces can extend other interfaces interfaces can extend other interfaces � allow a form of multiple inheritance � allow a form of multiple inheritance CS 307 Fundamentals of CS 307 Fundamentals of 9 10 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes The Comparable Interface Comparable Interface version 1.4 � The Java Standard Library package java.lang contains a number of interfaces – names are italicized in the class public interface Comparable listing { public int compareTo( Object other ); public int compareTo( Object other ); � One of the most important } interfaces is the Comparable interface � compareTo should return an int <0 if the calling object is less than the parameter, 0 if they are object is less than the parameter, 0 if they are equal, and an int >0 if the calling object is greater than the parameter CS 307 Fundamentals of 11 CS 307 Fundamentals of 12 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes

  72. Example compareTo Implementing Comparable � Any class that has a natural ordering of its � Suppose we have a class to objects (that is objects of that type can be model playing cards sorted based on some internal attribute) – Ace of Spades, King of Hearts, should implement the Comparable interface Two of Clubs � each card has a suit and a � Back to the ClosedShape example value, represented by ints � Suppose we want to be able to sort Suppose e a o be ab e o so � this version of compareTo will ClosedShape s and it is to be based on area compare values first and then p break ties with suits CS 307 Fundamentals of CS 307 Fundamentals of 13 14 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes compareTo in a Card class Interfaces and Polymorphism � Interfaces may be used as the data type public class Card implements Comparable { for object variables public int compareTo(Object otherObject) { { C Card other = (Card)otherObject; d th (C d) th Obj t � Can’t simply create objects of that type int result = this.myRank - other.myRank; if(result == 0) � Can refer to any objects that implement the � Can refer to any objects that implement the result = this.mySuit - other.mySuit; result = this mySuit - other mySuit; return result interface or descendants } // ot e // other methods not shown et ods ot s o � Ass me C � Assume Card implements Comparable d implements C bl } Card c = new Card(); Comparable comp1 = new Card(); Assume ints for ranks (2, 3, 4, 5, 6,...) and suits (0 is Comparable comp2 = c; clubs, 1 is diamonds, 2 is hearts, 3 is spades). CS 307 Fundamentals of 15 CS 307 Fundamentals of 16 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes

  73. Polymorphism Again! What can this Sort? What can this Sort? public static void SelSort(Comparable[] list) { Comparable temp; p p int smallest; for(int i = 0; i < list.length - 1; i++) Abstract Classes Abstract Classes { small = i; { ; for(int j = i + 1; j < list.length; j++) { if( list[j].compareTo(list[small]) < 0) small = j; ll j Part Class, part Interface } // end of j loop temp = list[i]; list[i] = list[small]; list[small] = temp; } // end of i loop } CS 307 Fundamentals of CS 307 Fundamentals of 17 18 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes The ClosedShape class Back to the ClosedShape Example � One behavior we might want in public class ClosedShape { private double myX; ClosedShapes is a way to get the area private double myY; � problem: How do I get the area of something public double getArea() { //Hmmmm?!?! that is “just a ClosedShape”? } // } // Other methods not shown Doesn’t seem like we have enough information to get the area if all we know is it is a ClosedShape. CS 307 Fundamentals of 19 CS 307 Fundamentals of 20 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes

  74. Leave it to the Sub - Classes Options // no getArea() in ClosedShape 1. Just leave it for the sub classes. public void printAreas(ClosedShape[] shapes) � Have each sub class define getArea() if they { for( ClosedShape s : shapes ) f ( Cl dSh h ) want to. { System.out.println( s.getArea() ); 2. Define getArea() in ClosedShape and } } simply return 0. ClosedShape[] shapes = new ClosedShape[2]; � Sub classes can override the method with more shapes[0] = new Rectangle(1 shapes[0] = new Rectangle(1, 2, 3, 4); 2 3 4); meaningful behavior. shapes[1] = new Circle(1, 2, 3); printAreas( shapes ); Will the above code compile? How does the compiler determine if a method call is allowed? ll i ll d? CS 307 Fundamentals of CS 307 Fundamentals of 21 22 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes Fix by Casting Fix with Dummy Method // getArea() in ClosedShape returns 0 // getArea() in ClosedShape returns 0 // // no getArea() in ClosedShape tA () i Cl dSh public void printAreas(ClosedShape[] shapes) public void printAreas(ClosedShape[] shapes) { { for( ClosedShape s : shapes ) for( ClosedShape s : shapes ) { if( s instanceof Rectangle ) { System.out.println( s.getArea() ); System.out.println( ((Rectangle)s).getArea() ); } else if( s instanceof Circle ) e se ( s sta ceo C c e ) } System.out.println( ((Circle)s).getArea() ); } } ClosedShape[] shapes = new ClosedShape[2]; shapes[0] = new Rectangle(1, 2, 3, 4); ClosedShape[] shapes = new ClosedShape[2]; shapes[1] = new Circle(1, 2, 3); shapes[0] = new Rectangle(1, 2, 3, 4); printAreas( shapes ); shapes[1] = new Circle(1, 2, 3); printAreas( shapes ); i tA ( h ) What happens if sub classes don’t override getArea()? What happens as we add more sub classes of ClosedShape ? Does that make sense? Does that make sense? Wh t h What happens if one of the objects is just a ClosedShape ? if f th bj t i j t ? CS 307 Fundamentals of 23 CS 307 Fundamentals of 24 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes

  75. A Better Fix Making getArea Abstract public class ClosedShape bli l Cl dSh � We know we want to be able to find the area { private double myX; of objects that are instances of private double myY; ClosedShape public abstract double getArea(); � The problem is we don’t know how to do that // I know I want it. // I know I want it. if all we know is it a ClosedShape // Just don’t know how, yet… � Make getArea an abstract method g } � Java keyword // Other methods not shown M th d th t Methods that are declared abstract have no body d l d b t t h b d an undefined behavior. All methods in an interface are abstract. CS 307 Fundamentals of CS 307 Fundamentals of 25 26 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes Undefined Behavior = Bad Problems with Abstract Methods � Not good to have undefined behaviors Given getArea() is now an abstract method � If a class has 1 or more abstract methods, what is wrong with the following code? what is wrong with the following code? the class must also be declared abstract. – version of ClosedShape shown would cause a ClosedShape s = new ClosedShape(); p p () compile error System.out.println( s.getArea() ); � Even if a class has zero abstract methods a programmer can still choose to make it abstract – if it models some abstract thing – is there anything that is just a “Mammal”? is there anything that is just a Mammal ? CS 307 Fundamentals of 27 CS 307 Fundamentals of 28 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes

  76. Abstract Classes Abstract Classes public abstract class ClosedShape public abstract class ClosedShape � In other words you can’t create instances of { private double myX; private double myY; objects where the lowest or most specific class type is an abstract class public abstract double getArea(); // I know I want it. � Prevents having an object with an undefined // Just don’t know how, yet… , y behavior } � Why would you still want to have // Other methods not shown y ou d you s a o a e constructors in an abstract class? if a class is abstract the compiler will not allow � Object variables of classes that are abstract Object variables of classes that are abstract constructors of that class to be called constructors of that class to be called ClosedShape s = new ClosedShape(1,2); types may still be declared //syntax error y ClosedShape s; //okay ClosedShape s; //okay CS 307 Fundamentals of CS 307 Fundamentals of 29 30 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes Implementing getArea() Sub Classes of Abstract Classes p public class Rectangle extends ClosedShape g p � Classes that extend an abstract class must { private double myWidth; private double myHeight; provided a working version of any abstract public double getArea() public double getArea() methods from the parent class { return myWidth * myHeight; } – or they must be declared to be abstract as well // other methods not shown } – could still decide to keep a class abstract regardless of status of abstract methods public class Square extends Rectangle { { public Square() public Square() { } public Square(double side) { super(side, side); } { ( id id ) } public Square(double x, double y, double side) { { super(side, side, x, y); } p ( , , , y); } } CS 307 Fundamentals of 31 CS 307 Fundamentals of 32 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes

  77. Polymorphism in Action A Circle Class public class UsesShapes public class Circle extends ClosedShape { public static void go() { public static void go() { { double dMyRadius; d bl dM R di { ClosedShape[] sList = new ClosedShape[10]; double a, b, c, d; public Circle() int x; { super(0,0); } for(int i = 0; i < 10; i++) ( ) { a = Math.random() * 100; public Circle(double radius) b = Math.random() * 100; { super(0,0); c = Math.random() * 100; d = Math.random() * 100; dMyRadius = radius; y ; x = (int)(Math.random() * 3 ); } if( x == 0 ) sList[i] = new Rectangle(a,b,c,d); public Circle(double x, double y, double radius) else if(x == 1) { super(x,y); { super(x y); sList[i] = new Square(a, c, d); Li t[i] S ( d) dMyRadius = radius; else } sList[i] = new Circle(a, c, d); } double total = 0 0; double total = 0.0; public double getArea() public double getArea() for(int i = 0; i < 10; i++) { return Math.PI * dMyRadius * dMyRadius; } { total += sList[i].getArea(); System.out.println( sList[i] ); public String toString() } } { return super.toString() + " radius: " + dMyRadius; } } } } CS 307 Fundamentals of CS 307 Fundamentals of 33 34 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes The Kicker Comparable in ClosedShape � We want to expand our pallet of shapes � We want to expand our pallet of shapes public abstract class ClosedShape implements Comparable public abstract class ClosedShape implements Comparable { private double myX; � Triangle could also be a sub class of ClosedShape. private double myY; – it would inherit from ClosedShape it would inherit from ClosedShape public abstract double getArea(); public double getArea() public int compareTo(Object other) { return 0.5 * dMyWidth * dMyHeight;} { { int result; int result; � What changes do we have to make to the code on ClosedShape otherShape = (ClosedShape)other; double diff = getArea() – otherShape.getArea(); the previous slide for totaling area so it will now if( diff == 0 ) result = 0; result = 0; handle Triangles as well? else if( diff < 0 ) result = -1; � Inheritance is can be described as new code using else old code. result = 1; return result � Polymorphism can be described as old code } } } using new code. i d CS 307 Fundamentals of 35 CS 307 Fundamentals of 36 Computer Science Interfaces and Abstract Classes Computer Science Interfaces and Abstract Classes

  78. About ClosedShapes compareTo � don’t have to return -1, 1. – Any int less than 0 or int greater than 0 based on 2 objects � the compareTo method makes use of the getArea() method which is abstract in ClosedShape – how is that possible? CS 307 Fundamentals of 37 Computer Science Interfaces and Abstract Classes

  79. Is This Algorithm Fast? Topic Number 8 op c u be 8 � Problem: given a problem, how fast does this Algorithm Analysis code solve that problem? � Could try to measure the time it takes, but " bit twiddling: 1. (pejorative) An exercise in tuning that is subject to lots of errors (see tune ) in which incredible amounts of time and – multitasking operating system effort go to produce little noticeable improvement, – speed of computer p p often with the result that the code becomes ft ith th lt th t th d b – language solution is written in incomprehensible." - The Hackers Dictionary, version 4.4.7 The Hackers Dictionary version 4 4 7 CS 307 Fundamentals of CS 307 Fundamentals of 1 2 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Attendance Question 1 Grading Algorithms � "My program finds all the primes between 2 � What we need is some way to grade and 1,000,000,000 in 1.37 seconds." algorithms and their representation via computer programs for efficiency – how good is this solution? – both time and space efficiency are concerns A. Good – are examples simply deal with time, not space B. Bad � The grades used to characterize the g C. It depends C It depends algorithm and code should be independent of platform, language, and compiler p , g g , p – We will look at Java examples as opposed to pseudocode algorithms CS 307 Fundamentals of 3 CS 307 Fundamentals of 4 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  80. Typical Big O Functions – "Grades" Big O Function Function Common Name Common Name � The most common method and notation for N! factorial discussing the execution time of algorithms is 2 2 N Exponential Exponential "Big O" N d , d > 3 Polynomial � Big O is the asymptotic execution time of the N 3 Cubic algorithm N 2 Quadratic � Big O is an upper bounds g O s a uppe bou ds N N N Square root N N log N N log N � It is a mathematical tool N Linear � Hide a lot of unimportant details by assigning � Hide a lot of unimportant details by assigning N Root - n a simple grade (function) to algorithms log N Logarithmic 1 Constant CS 307 Fundamentals of CS 307 Fundamentals of 5 6 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Big O Functions Actual vs. Big O � N is the size of the data set. � The functions do not include less dominant Simplified p terms and do not include any coefficients. Time � 4N 2 + 10N – 100 is not a valid F(N). 0 00 s ot a a d ( ) for Actual algorithm – It would simply be O(N 2 ) to � It is possible to have two independent � It is possible to have two independent complete l t variables in the Big O function. – example O(M + log N) example O(M + log N) – M and N are sizes of two different, but interacting Amount of data data sets data sets CS 307 Fundamentals of 7 CS 307 Fundamentals of 8 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  81. Formal Definition of Big O What it Means � T(N) is O( F(N) ) if there are positive � T(N) is the actual growth rate of the constants c and N 0 such that T(N) < cF(N) algorithm when N > N 0 – can be equated to the number of executable statements in a program or chunk of code – N is the size of the data set the algorithm works on � F(N) is the function that bounds the growth – T(N) is a function that characterizes the actual running time of the algorithm rate – F(N) is a function that characterizes an upper – may be upper or lower bound bounds on T(N). It is a limit on the running time of � T(N) may not necessarily equal F(N) ( ) y y q ( ) the algorithm. (The typical Big functions table) the algorithm (The t pical Big f nctions table) – constants and lesser terms ignored because it is – c and N 0 are constants a bounding function g CS 307 Fundamentals of CS 307 Fundamentals of 9 10 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Yuck Counting Statements in Code � How do you apply the definition? � H � So what constitutes a statement? d l h d fi i i ? � Hard to measure time without running programs � Can’t I rewrite code and get a different and that is full of inaccuracies d th t i f ll f i i answer, that is a different number of � Amount of time to complete should be directly statements? proportional to the number of statements executed proportional to the number of statements executed � Yes, but the beauty of Big O is, in the end for a given amount of data you ge you get the same answer e sa e a s e � Count up statements in a program or method or � Count up statements in a program or method or – remember, it is a simplification algorithm as a function of the amount of data – This is one technique This is one technique � Traditionally the amount of data is signified by the variable N CS 307 Fundamentals of 11 CS 307 Fundamentals of 12 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  82. Assumptions in For Counting Statements Counting Statements in Loops � Once found accessing the value of a primitive is Once found accessing the value of a primitive is Attendenance Question 2 Attendenance Question 2 constant time. This is one statement: � Counting statements in loops often requires x = y; //one statement a bit of informal mathematical induction � mathematical operations and comparisons in � What is output by the following code? boolean expressions are all constant time. int total = 0; x = y * 5 + z % 3; // one statement for(int i = 0; i < 2; i++) � if statement constant time if test and maximum time total += 5; for each alternative are constants System.out.println( total ); if( iMySuit == DIAMONDS || iMySuit == HEARTS ) A. 2 B. 5 C. 10 D. 15 E. 20 return RED; return RED; else return BLACK; // 2 statements (boolean expression + 1 return) // 2 t t t (b l i 1 t ) CS 307 Fundamentals of CS 307 Fundamentals of 13 14 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Counting Statements Attendances Question 3 in Nested Loops in Nested Loops � What is output by the following code? What is output by the following code? int total = 0; Attendance Question 4 // assume limit is an int >= 0 � What is output by the following code? What is output by the following code? for(int i = 0; i < limit; i++) int total = 0; total += 5; for(int i = 0; i < 2; i++) for(int j = 0; j < 2; j++) for(int j 0; j < 2; j++) System.out.println( total ); total += 5; A. 0 System.out.println( total ); A. 0 B. limit B. 10 C. limit 5 C limit * 5 C. 20 C 20 D. 30 D. limit * limit E. 40 E. limit 5 it 5 E li CS 307 Fundamentals of 15 CS 307 Fundamentals of 16 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  83. Attendance Question 5 Loops That Work on a Data Set � What is output by the following code? What is output by the following code? � The number of executions of the loop int total = 0; depends on the length of the array, values. // assume limit is an int >= 0 for(int i = 0; i < limit; i++) f (i t i 0 i < li it i++) public int total(int[] values) for(int j = 0; j < limit; j++) { int result = 0; total += 5; for(int i = 0; i < values.length; i++) for(int i = 0; i < values length; i++) System.out.println( total ); result += values[i]; return result; A. 5 } } B. limit * limit � How many many statements are executed C limit * limit * 5 C. limit limit 5 b by the above method h b h d D. 0 � N = values.length. What is T(N)? F(N)? E. limit 5 it 5 E li CS 307 Fundamentals of CS 307 Fundamentals of 17 18 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Counting Up Statements Showing O(N) is Correct � Recall the formal definition of Big O � int result = 0; 1 time � int i = 0; 1 time – T(N) is O( F(N) ) if there are positive constants c and N 0 such that T(N) < cF(N) when N > N 0 � i < values.length ; N + 1 times � In our case given T(N) = 3N + 4, prove the � i++ N times i++ N times method is O(N). � result += values[i]; N times – F(N) is N � return total; 1 time 1 i � We need to choose constants c and N 0 � T(N) = 3N + 4 � how about c = 4 N 0 = 5 ? how about c 4, N 0 5 ? � F(N) = N � Big O = O(N) Big O = O(N) CS 307 Fundamentals of 19 CS 307 Fundamentals of 20 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  84. vertical axis: time for algorithm to complete. (approximate with Attendance Question 6 number of executable statements) c * F(N) in this case c F(N), in this case, � Which of the following is true? c = 4, c * F(N) = 4N A. Method total is O(N) B. Method total is O(N 2 ) T(N), actual function of time. C. Method total is O(N!) C Method total is O(N!) In this case 3N + 4 In this case 3N + 4 D. Method total is O(N N ) E All E. All of the above are true f h b F(N), approximate function of time. In this case N N o = 5 horizontal axis: N, number of elements in data set horizontal axis: N number of elements in data set CS 307 Fundamentals of CS 307 Fundamentals of 21 22 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Just Count Loops, Right? It is Not Just Counting Loops // Second example from previous slide could be // S d l f i lid ld b // assume mat is a 2d array of booleans // rewritten as follows: // assume mat is square with N rows, int numThings = 0; int numThings = 0; // and N columns if( mat[r-1][c-1] ) numThings++; int numThings = 0; g ; if( mat[r-1][c] ) numThings++; ( [ ][ ] ) g ; for(int r = row - 1; r <= row + 1; r++) if( mat[r-1][c+1] ) numThings++; for(int c = col - 1; c <= col + 1; c++) if( mat[r][c-1] ) numThings++; if( mat[r][c] ) if( mat[ ][c] ) if( mat[r][c] ) numThings++; numThings++; if( mat[r][c+1] ) numThings++; if( mat[r+1][c-1] ) numThings++; What is the order of the above code? if( mat[r+1][c] ) numThings++; C. O(N 2 ) D. O(N 3 ) E. O(N 1/2 ) A. O(1) B. O(N) if( mat[r+1][c+1] ) numThings++; if( mat[r+1][c+1] ) numThings++; CS 307 Fundamentals of 23 CS 307 Fundamentals of 24 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  85. Sidetrack, the logarithm When Do Logarithms Occur � Algorithms have a logarithmic term when they use Algorithms have a logarithmic term when they use � Th � Thanks to Dr. Math k t D M th a divide and conquer technique � 3 2 = 9 � the data set keeps getting divided by 2 the data set keeps getting divided by 2 � likewise log 3 9 = 2 public int foo(int n) { // pre n > 0 – "The log to the base 3 of 9 is 2." int total = 0; int total 0; � The way to think about log is: while( n > 0 ) { n = n / 2; – "the log to the base x of y is the number you can total++; raise x to to get y." } return total; – Say to yourself "The log is the exponent." (and say } it over and over until you believe it.) it over and over until you believe it ) � What is the order of the above code? – In CS we work with base 2 logs, a lot A. O(1) B. O(logN) C. O(N) � log 32 = ? log 2 32 = ? log 2 8 = ? log 2 1024 = ? log 10 1000 = ? log 8 = ? log 1024 = ? log 1000 = ? D. O(Nlog N) E. O(N 2 ) CS 307 Fundamentals of CS 307 Fundamentals of 25 26 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Dealing with other methods Dealing With Other Methods � Wh t d � What do I do about method calls? I d b t th d ll ? public int foo(int[] list){ bli i t f (i t[] li t){ int total = 0; double sum = 0.0; for(int i = 0; i < list.length; i++){ g for(int i = 0; i < n; i++) for(int i = 0; i < n; i++) total += countDups(list[i], list); sum += Math.sqrt(i); } � Long way Long way return total; t t t l – go to that method or constructor and count } statements // method countDups is O(N) where N is the p � Short way // length of the array it is passed What is the Big O of foo ? g – substitute the simplified Big O function for that p g method. A. O(1) B. O(N) C. O(NlogN) – if Math.sqrt is constant time, O(1), simply count D O(N 2 ) D. O(N 2 ) E O(N!) E. O(N!) sum += Math.sqrt(i); as one statement. M th t(i) t t t CS 307 Fundamentals of 27 CS 307 Fundamentals of 28 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  86. Quantifiers on Big O Best, Average, Worst Case � It i � It is often useful to discuss different cases for ft f l t di diff t f � T � To Determine the best, average, and worst D t i th b t d t an algorithm case Big O we must make assumptions about the data set about the data set � Best Case: what is the best we can hope for? � Best case -> what are the properties of the data set – least interesting that will lead to the fewest number of executable that will lead to the fewest number of executable � Average Case (a.k.a. expected running time): statements (steps in the algorithm) � Worst case -> what are the properties of the data what usually happens with the algorithm? y pp g set that will lead to the largest number of � Worst Case: what is the worst we can expect executable statements of the algorithm? of the algorithm? � Average case > Usually this means assuming the � Average case -> Usually this means assuming the – very interesting to compare this to the average case data is randomly distributed – or if I ran the algorithm a large number of times with different sets of data what would the average amount of work be for those runs? CS 307 Fundamentals of CS 307 Fundamentals of 29 30 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Another Example Independent Loops public double minimum(double[] values) // from the Matrix class { int n = values.length; public void scale(int factor){ d double minValue = values[0]; bl i V l l [0] for(int r = 0; r < numRows(); r++) for(int i = 1; i < n; i++) for(int c = 0; c < numCols(); c++) if(values[i] < minValue) if(values[i] < minValue) iCells[r][c] *= factor; iCells[r][c] *= factor; minValue = values[i]; } return minValue; Assume an numRows() = N and numCols() = N. Assume an numRows() N and numCols() N. } In other words, a square Matrix. � T(N)? F(N)? Big O? Best case? Worst Case? What is the T(N)? What is the Big O? ( ) g Average Case? A. O(1) B. O(N) C. O(NlogN) � If no other information, assume asking average case D. O(N 2 ) ( ) E. O(N!) ( ) CS 307 Fundamentals of 31 CS 307 Fundamentals of 32 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  87. Replace Zeros – Typical Solution Significant Improvement – Algorithm with Smaller Big O function with Smaller Big O function public void replace0s(int[] data){ int max; for(int i = 0; i < data.length -1; i++){ for(int i = 0; i < data length 1; i++){ � P � Problem: Given an array of ints replace any bl Gi f i t l if( data[i] == 0 ){ element equal to 0 with the maximum value max = 0; to the right of that element. t th i ht f th t l t for(int j = i+1; j<data.length;j++) max = Math.max(max, data[j]); Given: data[i] = max; data[i] = max; [0, 9, 0, 8, 0, 0, 7, 1, -1, 0, 1, 0] } } Becomes: } [ 9 , 9, 8 , 8, 7 , 7 , 7, 1, -1, 1 , 1, 0] Assume most values are zeros. Example of a dependent loops Example of a dependent loops . CS 307 Fundamentals of CS 307 Fundamentals of 33 34 Computer Science Algorithm Analysis Computer Science Algorithm Analysis A Caveat Replace Zeros – Alternate Solution � What is the Big O of this statement in Java? public void replace0s(int[] data){ int max = Math.max(0, data[data.length – 1]); ( , [ g ]); int start = data.length – 2; int[] list = new int[n]; for(int i = start; i >= 0; i--){ if( data[i] == 0 ) ( [ ] ) data[i] = max; A. O(1) B. O(N) C. O(NlogN) else max = Math.max(max, data[i]); ( , [ ]); D O(N 2 ) D. O(N 2 ) E O(N!) E. O(N!) } } Big O of this approach? Big O of this approach? � Why? A.O(1) B. O(N) C. O(NlogN) D O(N 2 ) D. O(N 2 ) E. O(N!) E O(N!) CS 307 Fundamentals of 35 CS 307 Fundamentals of 36 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  88. Summing Executable Statements Example of Dominance � If an algorithms execution time is N 2 + N the � 2 � Look at an extreme example. Assume the it is said to have O(N 2 ) execution time not actual number as a function of the amount of O(N 2 + N) 2 data is: � When adding algorithmic complexities the N 2 /10000 + 2Nlog 10 N+ 100000 10 � Is it plausible to say the N 2 term dominates larger value dominates � formally a function f(N) dominates a function o a y a u c o ( ) do a es a u c o e e even though it is divided by 10000 and that oug s d ded by 0000 a d a g(N) if there exists a constant value n 0 such the algorithm is O(N 2 )? that for all values N > N 0 it is the case that � What if we separate the equation into What if we separate the equation into 0 g(N) < f(N) (N 2 /10000) and (2N log 10 N + 100000) and graph the results. graph the results CS 307 Fundamentals of CS 307 Fundamentals of 37 38 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Summing Execution Times Comparing Grades � Assume we have a problem � Algorithm A solves the problem correctly and red line is is O(N 2 ) 2Nlog10 N + 100000 � Algorithm B solves the same problem go t so es t e sa e p ob e blue line is blue line is N 2 /10000 correctly and is O(N log 2 N ) � Which algorithm is faster? Which algorithm is faster? � One of the assumptions of Big O is that the � For large values of N the N 2 term dominates so the For large values of N the N term dominates so the data set is large. data set is large algorithm is O(N 2 ) � The "grades" should be accurate tools if this � When does it make sense to use a computer? i t is true CS 307 Fundamentals of 39 CS 307 Fundamentals of 40 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  89. Running Times Theory to Practice OR Dykstra says: Pictures are for the Weak. Dykstra says: "Pictures are for the Weak " � Assume N = 100,000 and processor speed is 1,000,000,000 operations per second 1000 2000 4000 8000 16000 32000 64000 128K Function Running Time 2.2x10 -5 2.7x10 -5 5.4x10 -5 4.2x10 -5 O(N) 6.8x10 -5 1.2x10 -4 2.3x10 -4 5.1x10 -4 2 N 3.2 x 10 30086 years 8.5x10 -5 1.9x10 -4 3.7x10 -4 4.7x10 -4 O(NlogN) ( g ) 1.0x10 -3 2.1x10 -3 4.6x10 -3 1.2x10 -2 N 4 3171 years 3.5x10 -5 6.9x10 -4 1.7x10 -3 5.0x10 -3 N 3 11.6 days O(N 3/2 ) 1.4x10 -2 3.8x10 -2 0.11 0.30 N 2 N 10 seconds 10 seconds (55) (55) 3.4x10 -3 1.4x10 -3 4.4x10 -3 0.22 O(N 2 ) ind. 0.86 3.45 13.79 N N 0.032 seconds O(N 2 ) N log N 0.0017 seconds (27.6) 1.8x10 -3 7.1x10 -3 2.7x10 -2 0.11 0.43 1.73 6.90 dep dep. N 0.0001 seconds (1745) (7.2m) (13,957) (112k) (896k) (218) O(N 3 ) 3.2 x 10 -7 seconds 3.40 27.26 233 min 31 hrs 10 days 29 min. 80 days N 1 2 x 10 -8 seconds log N log N 1.2 x 10 seconds Times in Seconds. Red indicates predicated value. CS 307 Fundamentals of CS 307 Fundamentals of 41 42 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Change between Data Points Okay, Pictures Results on a 2GhZ laptop 1000 2000 4000 8000 16000 32000 64000 128K 256k 512k 4.0 1 21 1.21 2 02 2.02 0 78 0.78 1 62 1.62 1.76 1 76 1 89 1.89 2.24 2 24 2.11 2 11 1 62 1.62 - O(N) 3.5 O(NlogN) - 2.18 1.99 1.27 2.13 2.15 2.15 2.71 1.64 2.40 3.0 2.5 N - 1.98 2.48 2.87 2.79 2.76 2.85 2.79 2.82 2.81 O(N 3/2 ) NlogN Time 2.0 NsqrtN N^2 O(N 2 ) ind - O(N 2 ) i d - 4.06 4 06 3.98 3 98 3.94 3 94 3 99 3.99 4.00 4 00 3 99 3.99 - - - 1.5 N^2 O(N 2 ) 1.0 - 4.00 3.82 3.97 4.00 4.01 3.98 - - - dep p 0.5 0 5 - 8.03 - - - - - - - - O(N 3 ) 0.0 0 5000 10000 15000 20000 25000 30000 35000 Value obtained by Time x / Time x-1 V l bt i d b Ti / Ti V l Value of N f N CS 307 Fundamentals of 43 CS 307 Fundamentals of 44 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  90. Put a Cap on Time No O(N^2) Data Results on a 2GhZ laptop Results on a 2GhZ laptop 0.20 3.00 0.18 2.50 0.16 0.14 2.00 2 00 N 0.12 NlogN N Time Time 0.10 NsqrtN 1.50 NlogN N^2 NsqrtN 0.08 0 08 N^2 1.00 0.06 0.04 0.50 0.02 0.00 0.00 0 100000 200000 300000 400000 500000 600000 0 5000 10000 15000 20000 25000 30000 35000 Value of N Value of N Value of N V l f N CS 307 Fundamentals of CS 307 Fundamentals of 45 46 Computer Science Algorithm Analysis Computer Science Algorithm Analysis Just O(N) and O(NlogN) Just O(N) N Results on a 2GhZ laptop 0.0020 0.06 0.0018 0.05 0.0016 0.0014 0.04 0.0012 Time N 0.03 NlogN 0.0010 N 0.02 0.0008 0.0006 0.01 0.0004 0 0004 0.00 0.0002 0 100000 200000 300000 400000 500000 600000 Value of N 0.0000 0 0 100000 100000 200000 200000 300000 300000 400000 400000 500000 500000 600000 600000 CS 307 Fundamentals of 47 CS 307 Fundamentals of 48 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  91. Reasoning about algorithms A Useful Proportion � We have an O(N) algorithm, � W h O(N) l i h � Since F(N) is characterizes the running time – For 5,000 elements takes 3.2 seconds of an algorithm the following proportion – For 10,000 elements takes 6.4 seconds For 10 000 elements takes 6 4 seconds should hold true: – For 15,000 elements takes ….? F(N 0 ) / F(N 1 ) ~= time 0 / time 1 0 1 0 1 – For 20 000 elements takes For 20,000 elements takes ….? ? � An algorithm that is O(N 2 ) takes 3 seconds to run given 10,000 pieces of data. o u g e 0,000 p eces o da a � We have an O(N 2 ) algorithm We have an O(N ) algorithm – For 5,000 elements takes 2.4 seconds – How long do you expect it to take when there are – For 10,000 elements takes 9.6 seconds 30,000 pieces of data? , p – For 15,000 elements takes …? – common mistake – For 20,000 elements takes …? – logarithms? logarithms? CS 307 Fundamentals of CS 307 Fundamentals of 49 50 Computer Science Algorithm Analysis Computer Science Algorithm Analysis 10 9 instructions/sec, runtimes Why Use Big O? � As we build data structures Big O is the tool we will � A b ild d t t t Bi O i th t l ill O(N 2 ) N O(log N) O(N) O(N log N) use to decide under what conditions one data 0.000000003 0.00000001 0.000000033 0.0000001 10 structure is better than another s uc u e s be e a a o e 0.000000007 100 0.00000010 0.000000664 0.0001000 � Think about performance when there is a lot of 1,000 0.000000010 0.00000100 0.000010000 0.001 data. – "It worked so well with small data sets..." 0.000000013 0.00001000 0.000132900 0.1 min 10,000 – Joel Spolsky, Schlemiel the painter's Algorithm 0.000000017 100,000 0.00010000 0.001661000 10 seconds � Lots of trade offs � Lots of trade offs 1,000,000 0.000000020 0.001 0.0199 16.7 minutes – some data structures good for certain types of problems, 1,000,000,000 0.000000030 1.0 second 30 seconds 31.7 years bad for other types – often able to trade SPACE for TIME. – Faster solution that uses more space – Slower solution that uses less space Slower solution that uses less space CS 307 Fundamentals of 51 CS 307 Fundamentals of 52 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  92. Big O Space Formal Definition of Big O (repeated) � Less frequent in early analysis, but just as � T(N) is O( F(N) ) if there are positive important are the space requirements. constants c and N 0 such that T(N) < cF(N) when N > N 0 � Big O could be used to specify how much – N is the size of the data set the algorithm works on space is needed for a particular algorithm – T(N) is a function that characterizes the actual running time of the algorithm – F(N) is a function that characterizes an upper bounds on T(N). It is a limit on the running time of the algorithm the algorithm – c and N 0 are constants CS 307 Fundamentals of CS 307 Fundamentals of 53 54 Computer Science Algorithm Analysis Computer Science Algorithm Analysis What it All Means More on the Formal Definition � There is a point N 0 such that for all values of N that � Th � T(N) is the actual growth rate of the i i N h h f ll l f N h are past this point, T(N) is bounded by some algorithm multiple of F(N) multiple of F(N) – can be equated to the number of executable � Thus if T(N) of the algorithm is O( N^2 ) then, statements in a program or chunk of code ignoring constants at some point we can bound the ignoring constants, at some point we can bound the � F(N) is the function that bounds the growth running time by a quadratic function. rate � given a linear algorithm it is technically correct to given a linear algorithm it is technically correct to – may be upper or lower bound say the running time is O(N ^ 2). O(N) is a more precise answer as to the Big O of the linear � T(N) may not necessarily equal F(N) ( ) y y q ( ) algorithm – constants and lesser terms ignored because it is – thus the caveat “pick the most restrictive function” in Big a bounding function g O type questions. O t ti CS 307 Fundamentals of 55 CS 307 Fundamentals of 56 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  93. Other Algorithmic Analysis Tools Relative Rates of Growth Analysis Analysis Mathematical Mathematical Relative Relative � Big Omega T(N) is � ( F(N) ) if there are Type Expression Rates of positive constants c and N 0 such that Growth T(N) > cF( N )) when N > N 0 Big O T(N) = O( F(N) ) T(N) < F(N) – Big O is similar to less than or equal, an upper bounds Big � T(N) = � ( F(N) ) T(N) > F(N) – Big Omega is similar to greater than or equal, a lower bound l b d Big � T(N) = � ( F(N) ) T(N) = F(N) � Big Theta T(N) is � ( F(N) ) if and only if T(N) is O( F(N) )and T( N ) is � ( F(N) ). "In spite of the additional precision offered by Big Theta, – Big Theta is similar to equals Big O is more commonly used, except by researchers Big O is more commonly used except by researchers in the algorithms analysis field" - Mark Weiss CS 307 Fundamentals of CS 307 Fundamentals of 57 58 Computer Science Algorithm Analysis Computer Science Algorithm Analysis

  94. Topic 9 Introduction to Recursion I t d ti t R i Underneath the Hood. "T "To a man with a hammer, ith h everything looks like a nail everything looks like a nail" -Mark Twain Mark Twain CS 307 Fundamentals of CS 307 Fundamentals of 1 2 Computer Science Computer Science Introduction to Recursion Introduction to Recursion The Program Stack Methods for Illustration 200 public void someFooMethod(int z) 200 bli id F M th d(i t ) � When you invoke a method in your code 201{ int x = 2 * z; what happens when that method is 202 202 System.out.println(x); i l ( ) completed? } FooObject f = new FooObject(); int x = 3; 300 public void someBarMethod(int y) f.someFooMethod(x); 301 { 301 { int x = 3 * y; i 3 * f.someBarMethod(x); 302 someFooMethod(x); � How does that happen? pp 303 System.out.println(x); � What makes it possible? } CS 307 Fundamentals of 3 CS 307 Fundamentals of 4 Computer Science Computer Science Introduction to Recursion Introduction to Recursion

  95. The Program Stack Basic CPU Operations � A CPU works via a fetch � A CPU k i f t h � When your program is executed on a command / execute command processor the commands are converted into loop and a program counter loop and a program counter another set of instructions and assigned � Instructions stored in memory memory locations. (Just like data!) (Just like data!) – normally a great deal of expansion takes place 101 FooObject f = new FooObject(); 101 FooObject f = new FooObject(); j j (); 102 int x = 3; 102 int x = 3; 103 f.someFooMethod(x); 103 f.someFooMethod(x); 104 f 104 f.someBarMethod(x); B M th d( ) 104 f 104 f.someBarMethod(x); h d( ) � What if someFooMethod is stored at � Von Neumann Architecture memory location 200? memory location 200? CS 307 Fundamentals of CS 307 Fundamentals of 5 6 Computer Science Computer Science Introduction to Recursion Introduction to Recursion Activation Records and the More on the Program Stack Program Stack Program Stack 101 FooObject f = new FooObject(); � When a method is invoked all the relevant 102 int x = 3; i f information about the current method ti b t th t th d 103 f.someFooMethod(x); (variables, values of variables, next line of 104 f.someBarMethod(x); code to be executed) is placed in an d t b t d) i l d i � Line 103 is really saying go to line 200 with f activation record as the implicit parameter and x as the explicit � The activation record is pushed onto the parameter program stack � When someFooMethod is done what happens? pp � A stack is a data structure with a single A. Program ends B. goes to line 103 access point, the top. p , p C Goes back to whatever method called it C. Goes back to whatever method called it CS 307 Fundamentals of 7 CS 307 Fundamentals of 8 Computer Science Computer Science Introduction to Recursion Introduction to Recursion

  96. The Program Stack � Data may either be added ( pushed) or removed (popped) from top a stack but it is always Using Recursion Using Recursion f from the top. – A stack of dishes – which dish do we have easy access to? CS 307 Fundamentals of CS 307 Fundamentals of 9 10 Computer Science Computer Science Introduction to Recursion Introduction to Recursion A Problem Attendance Question 2 � Write a method that determines how much space is take up � W it th d th t d t i h h i t k � How many levels of directories have to be by the files in a directory visited? � A directory can contain files and directories A directory can contain files and directories A. 0 � How many directories does our code have to examine? � How would you add up the space taken up by the files in a B. Unknown U o single directory C. Infinite – Hint: don't worry about any sub directories at first � Directory and File classes � Directory and File classes D. 1 D 1 � in the Directory class: E. 8 public File[] getFiles() public Directory[] getSubdirectories() � in the File class public int getSize() bli i t tSi () CS 307 Fundamentals of 11 CS 307 Fundamentals of 12 Computer Science Computer Science Introduction to Recursion Introduction to Recursion

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend