JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Fall 2016 1
administrivia 2
-assignment 1 posted -due next Wednesday by midnight -TA office hours posted -Clicker registration 3
4
channel: 41 session: cs2420 5
last time 6
N -we refer to unspecified integer quantities as N -N is the problem size -sorting an array of N numbers -searching for an item in a set of N items -inserting an item into a set of N items -amount of work done for these operations usually depends on N -work required is a function of N 7
sort1 versus sort2 8
small N sort 1 sort 2 0.009 running time (miliseconds) 0.008 0.007 0.006 0.005 0.004 0.003 0.002 0.001 0 10 20 30 40 50 60 70 80 90 100 N (size of list) 9
medium N sort 1 sort 2 running time (miliseconds) 0.1 0.09 0.08 0.07 0.06 0.05 0.04 0.03 0.02 0.01 0 100 150 200 250 300 350 400 450 500 550 N (size of list) 10
large N sort 1 sort 2 running time (miliseconds) 30 25 20 15 10 5 0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 N (size of list) 11
take away: large N as N becomes large complexity matters! sort 1 sort 2 running time (miliseconds) 30 25 20 15 10 5 0 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 N (size of list) 11
sort1 selection sort void sort1(int[] arr) { for(int i = 0; i < arr.length-1; i++) { int j, minindex; for(j = i+1, minindex = i; j < arr.length; j++) if(arr[j] < arr[minindex]) } } minindex = j; swap(arr, i, minindex); best case: O(N 2 ) average case: O(N 2 ) worst case: O(N 2 ) sort2 quick sort void sort2(int[] arr, int beg, int end) { if (end > beg + 1) { int piv = arr[beg], l = beg + 1, r = end; while (l < r) { if (arr[l] <= piv) l++; else swap(arr, l, --r); } } } swap(arr, --l, beg); sort2(arr, beg, l); sort2(arr, r, end); 12 best case: O(N log N) average case: O(N log N) worst case: O(N 2 )
today 13
disclaimer: this class is not about teaching you Java 14
-variables -control flow -reference types -misc. -mini lab 15
variables 16
-a variable is a piece of data in memory with: -an identifier (name) -a type 17
-a variable is a piece of data in memory with: -an identifier (name) -a type -what is a type? 17
-a variable is a piece of data in memory with: -an identifier (name) -a type -what is a type? -a basic building block in a programming language -determines what kind of data a variable holds, and what operations can be performed on it 17
-a variable is a piece of data in memory with: -an identifier (name) -a type -what is a type? -a basic building block in a programming language -determines what kind of data a variable holds, and what operations can be performed on it -Java defines eight primitive types 17
-a variable is a piece of data in memory with: -an identifier (name) -a type -what is a type? -a basic building block in a programming language -determines what kind of data a variable holds, and what operations can be performed on it -Java defines eight primitive types -byte, short, int, long, float, double, char, boolean 17
-a variable is a piece of data in memory with: -an identifier (name) -a type -what is a type? -a basic building block in a programming language -determines what kind of data a variable holds, and what operations can be performed on it -Java defines eight primitive types -byte, short, int, long, float, double, char, boolean -each primitive type can hold a single value - r, 12, 2.64, true 17
declaration & initialization -declaring a variable is stating that it exists -assigns the variable a type and name boolean arewethereyet; -initializing a variable gives it an initial value, and is often combined with declaring boolean arewethereyet = false; -variables declared as final are constant and cannot be changed after initialization final int themeaningoflife = 42; 18
assignment -after a variable has been declared we can assign it a new value with = arewethereyet = true; -we can use arithmetic expressions with an assignment age = currentyear - birthyear; 19
arithmetic operations -explicitly supported on primitive types -binary operators -unary operators -Java follows common order-of-operation rules 20
arithmetic operations -explicitly supported on primitive types -binary operators +, -, *, /, % -unary operators -Java follows common order-of-operation rules 20
arithmetic operations -explicitly supported on primitive types -binary operators +, -, *, /, % -unary operators - (negation), ++ (increment), -- (decrement) -Java follows common order-of-operation rules 20
arithmetic operations -explicitly supported on primitive types -binary operators +, -, *, /, % -unary operators - (negation), ++ (increment), -- (decrement) -Java follows common order-of-operation rules unary ops : highest 20
arithmetic operations -explicitly supported on primitive types -binary operators +, -, *, /, % -unary operators - (negation), ++ (increment), -- (decrement) -Java follows common order-of-operation rules unary ops : highest *, /, % : high 20
arithmetic operations -explicitly supported on primitive types -binary operators +, -, *, /, % -unary operators - (negation), ++ (increment), -- (decrement) -Java follows common order-of-operation rules unary ops : highest *, /, % : high +, - : low 20
arithmetic operations -explicitly supported on primitive types -binary operators +, -, *, /, % -unary operators - (negation), ++ (increment), -- (decrement) -Java follows common order-of-operation rules unary ops : highest *, /, % : high +, - : low = : lowest 20
type conversion -widening conversions convert data to another type that has the same or more bits of storage -narrowing conversions convert data to another type that has fewer bits of storage 21
type conversion -widening conversions convert data to another type that has the same or more bits of storage short -> int int int -> long -> float -narrowing conversions convert data to another type that has fewer bits of storage 21
type conversion -widening conversions convert data to another type that has the same or more bits of storage short -> int int int -> long -> float -narrowing conversions convert data to another type that has fewer bits of storage double -> float float -> int 21
type conversion -widening conversions convert data to another type that has the same or more bits of storage short -> int int int -> long -> float -narrowing conversions convert data to another type that has fewer bits of storage double -> float float -> int what do you have to be careful about here? 21
type conversion -java uses widening conversion when an operator is applied to operands of different types (called promotion) 22
type conversion -java uses widening conversion when an operator is applied to operands of different types (called promotion) 2.2 * 2 1.0 / 2 double x = 2; count = + 4 22
type conversion -java uses widening conversion when an operator is applied to operands of different types (called promotion) 2.2 * 2 1.0 / 2 double x = 2; count = + 4 evaluates to 4.4 22
type conversion -java uses widening conversion when an operator is applied to operands of different types (called promotion) 2.2 * 2 1.0 / 2 double x = 2; count = + 4 evaluates to 4.4 evaluates to 0.5 22
type conversion -java uses widening conversion when an operator is applied to operands of different types (called promotion) 2.2 * 2 1.0 / 2 double x = 2; count = + 4 evaluates to 4.4 evaluates to 0.5 assigns 2.0 to x 22
type conversion -java uses widening conversion when an operator is applied to operands of different types (called promotion) 2.2 * 2 1.0 / 2 double x = 2; count = + 4 evaluates to 4.4 evaluates to 0.5 assigns 2.0 to x evaluates to count = 4 22
type conversion -java uses widening conversion when an operator is applied to operands of different types (called promotion) 2.2 * 2 1.0 / 2 double x = 2; count = + 4 evaluates to 4.4 evaluates to 0.5 assigns 2.0 to x evaluates to count = 4 string concatenation 22
mixing types -conversions are done on one operator at a time in the order the operators are evaluated 23
mixing types -conversions are done on one operator at a time in the order the operators are evaluated 3 / 2 * 3.0 + 8 / 3 23
mixing types -conversions are done on one operator at a time in the order the operators are evaluated 3 / 2 * 3.0 + 8 / 3 5.0 23
mixing types -conversions are done on one operator at a time in the order the operators are evaluated 3 / 2 * 3.0 + 8 / 3 5.0 2.0 * 4 / 5 + 6 / 4.0 23
mixing types -conversions are done on one operator at a time in the order the operators are evaluated 3 / 2 * 3.0 + 8 / 3 5.0 2.0 * 4 / 5 + 6 / 4.0 3.1 23
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 1x4 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 1x4 2+3= + 2 + 3 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 2+3= + 2 + 3 1x4 2+3=23 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 2+3= + 2 + 3 1x4 2+3=23 1 + 2 + 3 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 2+3= + 2 + 3 1 + 2 + 3 1x4 2+3=23 33 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 2+3= + 2 + 3 1 + 2 + 3 1x4 2+3=23 33 2*3= + 2 * 3 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 2+3= + 2 + 3 1 + 2 + 3 2*3= + 2 * 3 1x4 2+3=23 33 2*3=6 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 2+3= + 2 + 3 1 + 2 + 3 2*3= + 2 * 3 1x4 2+3=23 33 2*3=6 4-1 + x 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 2+3= + 2 + 3 1 + 2 + 3 2*3= + 2 * 3 4-1 + x 1x4 2+3=23 33 2*3=6 3x 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 2+3= + 2 + 3 1 + 2 + 3 2*3= + 2 * 3 4-1 + x 1x4 2+3=23 33 2*3=6 3x x + 4-1 24
mixing types -String concatenation has the same precedence as +- and is evaluated left to right 1 + x + 4 2+3= + 2 + 3 1 + 2 + 3 2*3= + 2 * 3 4-1 + x x + 4-1 1x4 2+3=23 33 2*3=6 3x error 24
type casting -type casting tells Java to convert one type to another -convert an int to a double to force floating-point division double average = (double) 12 / 5; -truncate a double to an int int feet = (int) (28.3 / 12.0); 25
assignment operators -basic assignment operator = -combined assignment/arithmetic operators +=, -=, *=, /= -increment/decrement operators can be stand-alone statements i++; i--; ++i; --i; 26
assignment operators -basic assignment operator = -combined assignment/arithmetic operators +=, -=, *=, /= -increment/decrement operators can be stand-alone statements int i = 3; i++; int j = i++; i--; System.out.println(i+ +j); ++i; --i; 26
assignment operators -basic assignment operator = -combined assignment/arithmetic operators +=, -=, *=, /= -increment/decrement operators can be stand-alone statements int i = 3; i++; int j = i++; i--; System.out.println(i+ +j); ++i; --i; int i = 3; int j = ++i; System.out.println(i+ +j); 26
relational and logical ops -results are always boolean -relational ops supported for number and character types (and equality for boolean) >, <, >=, <=, ==,!= -logical ops supported for boolean &&,,! -precedence (all lower than arithmetic): 27
relational and logical ops -results are always boolean -relational ops supported for number and character types (and equality for boolean) >, <, >=, <=, ==,!= -logical ops supported for boolean &&,,! -precedence (all lower than arithmetic): >, <, >=, <= : highest 27
relational and logical ops -results are always boolean -relational ops supported for number and character types (and equality for boolean) >, <, >=, <=, ==,!= -logical ops supported for boolean &&,,! -precedence (all lower than arithmetic): >, <, >=, <= : highest ==,!= : high 27
relational and logical ops -results are always boolean -relational ops supported for number and character types (and equality for boolean) >, <, >=, <=, ==,!= -logical ops supported for boolean &&,,! -precedence (all lower than arithmetic): >, <, >=, <= : highest ==,!= : high && : low 27
relational and logical ops -results are always boolean -relational ops supported for number and character types (and equality for boolean) >, <, >=, <=, ==,!= -logical ops supported for boolean &&,,! -precedence (all lower than arithmetic): >, <, >=, <= : highest ==,!= : high && : low : lowest 27
control flow 28
-control flow determines how programs make decisions about what to do, and how many times to do it -decision making : if-else, switch-case -looping : for, while, do-while -jumping : break, continue, return -exceptions : try-catch, throw 29
switch statements -similar to an if-else-if statement switch(integer expression) { case <integer literal>: list of statements } case <integer literal>: 30
switch statements -execution begins on the first case that matches the value of the switch variable -execution continues until break is reached 31
switch statements -execution begins on the first case that matches the value of the switch variable -execution continues until break is reached 31
switch statements -execution begins on the first case that matches the value of the switch variable -execution continues until break is reached 31
switch statements -execution begins on the first case that matches the value of the switch variable -execution continues until break is reached -even continues through other cases! -usually want a break after every case 31
switch statements -execution begins on the first case that matches the value of the switch variable -execution continues until break is reached -even continues through other cases! -usually want a break after every case -switches can use the default keyword -if no cases were hit, execute the default case -similar to an else at the end of a long line of ifelse-if 31
exceptions -an exception is a special event that interrupts the control of the program -exceptions are thrown explicitly by the code -use a try block to wrap any code that might throw an exception -a catch block immediately follows a try block -execution of the program jumps inside the catch block if an exception occurred within the try block 32
try { FileReader in = new FileReader( fakefile.txt ); } catch(filenotfoundexception e) { System.out.println( file does not exist ); } catch(exception e) // a less specific error occured { System.err.println(e.getMessage()); } 33
throwing exceptions if(arraysize < 0) throw new NegativeArraySizeException(); arr = new int[arraysize]; -why don t we need an else? (what are we assuming?) 34
throwing exceptions if(arraysize < 0) throw new NegativeArraySizeException(); arr = new int[arraysize]; -why don t we need an else? (what are we assuming?) -there are many many subclasses of exceptions 34
throwing exceptions if(arraysize < 0) throw new NegativeArraySizeException(); arr = new int[arraysize]; -why don t we need an else? (what are we assuming?) -there are many many subclasses of exceptions -you can even define your own! public class BadnessOccurred extends Exception { } 34
reference types 35
-all non-primitive types are reference types 36
-all non-primitive types are reference types -a reference is a variable that stores the memory address where an object (a group of values) resides 36
-all non-primitive types are reference types -a reference is a variable that stores the memory address where an object (a group of values) resides Point p1, p2, p3; p1 = new Point(7,19); p2 = p1; p2.x = 2; 36
-all non-primitive types are reference types -a reference is a variable that stores the memory address where an object (a group of values) resides Point p1, p2, p3; p1 = new Point(7,19); p2 = p1; p2.x = 2; p1 p2 p3 36
-all non-primitive types are reference types -a reference is a variable that stores the memory address where an object (a group of values) resides Point p1, p2, p3; p1 = new Point(7,19); p2 = p1; p2.x = 2; p1 null p2 null p3 null 36
-all non-primitive types are reference types -a reference is a variable that stores the memory address where an object (a group of values) resides Point p1, p2, p3; p1 = new Point(7,19); p2 = p1; p2.x = 2; p1 1024 p2 null p3 null 1024 7 19 36
-all non-primitive types are reference types -a reference is a variable that stores the memory address where an object (a group of values) resides Point p1, p2, p3; p1 = new Point(7,19); p2 = p1; p2.x = 2; p1 1024 p2 1024 p3 null 1024 7 19 36
-all non-primitive types are reference types -a reference is a variable that stores the memory address where an object (a group of values) resides Point p1, p2, p3; p1 = new Point(7,19); p2 = p1; p2.x = 2; p1 1024 p2 1024 p3 null 1024 2 19 36
reference declaration -declaration of a reference variable only provides a name to reference an object it does not create an object -after Point p1; the value stored in p1 is null 37
reference declaration -declaration of a reference variable only provides a name to reference an object it does not create an object -after Point p1; the value stored in p1 is null 37
reference declaration -declaration of a reference variable only provides a name to reference an object it does not create an object -after Point p1; the value stored in p1 is null -the new keyword is used to construct an object Point p1 = new Point(); Point p2; p2 = new Point(); 37
reference declaration -declaration of a reference variable only provides a name to reference an object it does not create an object -after Point p1; the value stored in p1 is null -the new keyword is used to construct an object Point p1 = new Point(); Point p2; p2 = new Point(); why are () needed? 37
operations on reference types -operations on references: =, ==,!= -equality operators compare addresses 38
operations on reference types -operations on references: =, ==,!= -equality operators compare addresses -what does p2 == p1 return? Point p1, p2, p3; p1 = new Point(7,19); p2 = p1; p1 1024 p2 1024 p3 null 1024 7 19 38
operations on reference types -operations on objects:., instanceof -the. operator is used to select a method that is applied to an object, or an individual component of an object Point p1, p2, p3; p1 = new Point(7,19); p2 = p1; p1 1024 p2 1024 p3 null 1024 7 19 39
operations on reference types -operations on objects:., instanceof -the. operator is used to select a method that is applied to an object, or an individual component of an object Point p1, p2, p3; p1 = new Point(7,19); p2 = p1; p1 1024 p2 1024 1024 7 19 what does p2.firstvalue() return? p3 null 39
operations on reference types -operations on objects:., instanceof -the. operator is used to select a method that is applied to an object, or an individual component of an object Point p1, p2, p3; p1 = new Point(7,19); p2 = p1; p1 1024 p2 1024 1024 7 19 what does p2.firstvalue() return? what does p1 instanceof Point return? p3 null 39
String -String is the only reference type for which operator overloading is allowed (+ and +=) -but you can t define your own operator overloads! -String objects are immutable -to compare String objects use equals and compareto methods not ==,!=, <, or > -why? -other useful String methods: -length, charat, substring 40
String s1 = Hello ; String s2 = s1; s1 = Good-bye ; System.out.println(s2); 41
String s1 = Hello ; String s2 = s1; s1 = Good-bye ; System.out.println(s2); s1 1024 1024 Hello 41
String s1 = Hello ; String s2 = s1; s1 = Good-bye ; System.out.println(s2); s1 1024 s2 1024 Hello 41
s1 String s1 = Hello ; 1024 String s2 = s1; s1 = Good-bye ; s2 System.out.println(s2); 2056 1024 Hello 2056 Hello 41
512 s1 String s1 = Hello ; 512 String s2 = s1; s1 = Good-bye ; s2 System.out.println(s2); 2056 GOOD-BYE 1024 Hello 2056 Hello 41
String -String is the only reference type for which operator overloading is allowed (+ and +=) -but you can t define your own operator overloads! -String objects are immutable -to compare String objects use equals and compareto methods not ==,!=, <, or > -why? -other useful String methods: -length, charat, substring 42
arrays -an array is a mechanism for storing a collection of identically typed entities -in Java, arrays behave like objects -the [] operator indexes an array, accessing an individual entity bounds checking is performed automatically -by default, array elements are initialized 0 (primitive types) and null (reference types) Point[] refarray = new Point[10]; double[] primarray = {3.14, 2.2, -9.8}; 43
ArrayList -the ArrayList class (from the Collections library) mimics an array and allows for dynamic expansion -the get,set methods are used in place of [] for indexing -the add method increases the size by one and adds a new item -ArrayList may only be used with reference types ArrayList<String> a = new ArrayList<String>(1); a.set(0, hi ); a.add( there ); 44
misc. 45
parameter passing -Java uses call-by-value parameter passing -ie. a copy is created int i = 4; modifyint(i); System.out.println(i); // what does this print? 46
parameter passing -Java uses call-by-value parameter passing -ie. a copy is created int i = 4; modifyint(i); System.out.println(i); // what does this print? -what does this mean for references? Point p = new Point(1, 2); modifypoint(p); System.out.println(p.x); // prints? 46
main -when a program is run, the main method is invoked p u b l i c s t a t i c v o i d m a i n ( S t r i n g [ ] a r g s ) -the parameters of main can be set using command-line arguments 47
classes & constructors -a class consists of fields (aka. variables) that store data and methods that operate on that data -fields and methods may be public or private -the constructor controls how an object is created and initialized -multiple constructors may be defined, taking different parameters -if none is defined, a default constructor is generated -initializes primitive fields to 0, and reference fields to null
classes & constructors -a class consists of fields (aka. variables) that store data and methods that operate on that data -fields and methods may be public or private -the constructor controls how an object is created and initialized -multiple constructors may be defined, taking different parameters -if none is defined, a default constructor is generated -initializes primitive fields to 0, and reference fields to null the difference between field and variable: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
this -this is a reference to the current object -useful in avoiding self-assignment 49
this -this is a reference to the current object -useful in avoiding self-assignment // transfer all money from rhs to current account public void finaltransfer( Account rhs ) { dollars += rhs.dollars; rhs.dollars = 0; } 49
this -this is a reference to the current object -useful in avoiding self-assignment Account account1; Account account2; account2 = account1; account1.finaltransfer( account2 ); // transfer all money from rhs to current account public void finaltransfer( Account rhs ) { dollars += rhs.dollars; rhs.dollars = 0; } 49
this -this is a reference to the current object -useful in avoiding self-assignment Account account1; Account account2; account2 = account1; account1.finaltransfer( account2 ); // transfer all money from rhs to current account public void finaltransfer( Account rhs ) { if ( this == rhs ) return; dollars += rhs.dollars; rhs.dollars = 0; } 50
next time 51
-reading -chapters 3 & 4 -homework -assignment 1 is up -due next Wednesday at midnight -must complete on your own! -lab -testing -clicker questions start next week 52