Presentation is loading. Please wait.

Presentation is loading. Please wait.

Shlomo Hershkop 2007 1 Advanced Review. Shlomo Hershkop 20072 Advanced Review Time classes Time classes Date Classes Date Classes File input/output File.

Similar presentations


Presentation on theme: "Shlomo Hershkop 2007 1 Advanced Review. Shlomo Hershkop 20072 Advanced Review Time classes Time classes Date Classes Date Classes File input/output File."— Presentation transcript:

1 Shlomo Hershkop 2007 1 Advanced Review

2 Shlomo Hershkop 20072 Advanced Review Time classes Time classes Date Classes Date Classes File input/output File input/output Packages Packages

3 Shlomo Hershkop 20073 Multiple dimensions No reason cant create 4,5,6 dimension arrays No reason cant create 4,5,6 dimension arrays Gets hard to manage Gets hard to manage Better idea: Better idea: Think about another way of representing the data Think about another way of representing the data Often creating an object is a better approach Often creating an object is a better approach

4 Shlomo Hershkop 20074 Arrays further Need to explicitly copy contents of arrays when resizing arrays with temp one Need to explicitly copy contents of arrays when resizing arrays with temp one Better solution: Better solution: ArrayList ArrayList Vector Vector Full object versions of arrays Full object versions of arrays Capacity can grow over time Capacity can grow over time Useful methods bundles with them Useful methods bundles with them

5 Shlomo Hershkop 20075 code Create a new class with a main called VectorTest Create a new class with a main called VectorTest Create a vector Create a vector Put in some stuff Put in some stuff Print them out Print them out Replace something in the middle Replace something in the middle Print it out Print it out Clear the vector Clear the vector Print it out Print it out

6 Shlomo Hershkop 20076 Default values Should be aware if you forget to set values Should be aware if you forget to set values Might mess up your logic Might mess up your logic Think of multiplying a bunch of numbers and not setting one of them… Think of multiplying a bunch of numbers and not setting one of them… Compiler/IDE will let you know if you forgot to set values (warning) Compiler/IDE will let you know if you forgot to set values (warning)

7 Shlomo Hershkop 20077 Time Next lets discuss how time is handled in Java Next lets discuss how time is handled in Java Java.util.Date is the way java represents a point in time Java.util.Date is the way java represents a point in time It is measured in milliseconds It is measured in milliseconds Time = 0 what does that mean? Time = 0 what does that mean?

8 Shlomo Hershkop 20078 Date Time 0 = first millisecond in 1970 Time 0 = first millisecond in 1970 Historical reasons for this Historical reasons for this long is the type it uses long is the type it uses Range to +9,223,372,036,854,775,807 Range to +9,223,372,036,854,775,807 Don’t memorize that Don’t memorize that Lets look at the API Lets look at the API What is a deprecated method ?? What is a deprecated method ?? Example: getDay() ?? Example: getDay() ??

9 Shlomo Hershkop 20079 Why Date Why are we wrapping the time long number? Why are we wrapping the time long number? "I'll see you on 996,321,998,346." doesn’t really work "I'll see you on 996,321,998,346." doesn’t really work Also allows you to easily order and compare different points in time….meaningfully Also allows you to easily order and compare different points in time….meaningfully

10 Shlomo Hershkop 200710 Change over time (no pun) Nothing you program should be set in stone Nothing you program should be set in stone Sometimes your design changes Sometimes your design changes Need to go back and change your code Need to go back and change your code Deprecated methods are those which have been replaced…but left in place so your old stuff shouldn’t crash if you try to recompile with latest jdk Deprecated methods are those which have been replaced…but left in place so your old stuff shouldn’t crash if you try to recompile with latest jdk

11 Shlomo Hershkop 200711 Back to time System.currentTimeMillis() System.currentTimeMillis() Returns the current time on the system Returns the current time on the system As a Date Object As a Date Object

12 Shlomo Hershkop 200712 Ideas Although would like to represent a point in time, usually time is associated with other measurements Although would like to represent a point in time, usually time is associated with other measurements Month Month Year Year

13 Shlomo Hershkop 200713 The GregorianCalendar Class The Date class doesn't measure months, weekdays, etc. The Date class doesn't measure months, weekdays, etc. That's the job of a calendar That's the job of a calendar A calendar assigns a name to a point in time A calendar assigns a name to a point in time Many calendars in use: Many calendars in use: Gregorian Gregorian Contemporary: Hebrew, Arabic, Chinese Contemporary: Hebrew, Arabic, Chinese Historical: French Revolutionary, Mayan Historical: French Revolutionary, Mayan

14 Shlomo Hershkop 200714 Relationships

15 Shlomo Hershkop 200715 Next step Lets design a new class to represent a day Lets design a new class to represent a day Today is Tuesday Today is Tuesday Day today = new Day(); Today.add(1); //should give us Wednesday

16 Shlomo Hershkop 200716 Goal of Day Class Answer questions such as Answer questions such as How many days are there between now and the end of the year? How many days are there between now and the end of the year? What day is 100 days from now? What day is 100 days from now? How many days till my birthday (I’ve always wanted a _____________) How many days till my birthday (I’ve always wanted a _____________)

17 Shlomo Hershkop 200717 Designing the class Lets have a method Lets have a method daysFrom it computes number of days between two days: daysFrom it computes number of days between two days: int n = today.daysFrom(birthday); addDays computes a day that is some days away from a given day: addDays computes a day that is some days away from a given day: Day later = today.addDays(999); Mathematical relationship: Mathematical relationship: d.addDays(n).daysFrom(d) == n d1.addDays(d2.daysFrom(d1)) == d2

18 Shlomo Hershkop 200718 Constructor Date(int year, int month, int date) Constructor Date(int year, int month, int date) Will need the following methods: Will need the following methods: getYear getYear getMonth getMonth getDate getDate

19 Shlomo Hershkop 200719 Implementation Straightforward which member will need: Straightforward which member will need: private int year private int month private int date addDays/daysBetween tedious to implement addDays/daysBetween tedious to implement April, June, September, November have 30 days April, June, September, November have 30 days February has 28 days, except in leap years it has 29 days February has 28 days, except in leap years it has 29 days All other months have 31 days All other months have 31 days Leap years are divisible by 4, except after 1582, years divisible by 100 but not 400 are not leap years Leap years are divisible by 4, except after 1582, years divisible by 100 but not 400 are not leap years There is no year 0; year 1 is preceded by year -1 There is no year 0; year 1 is preceded by year -1 In the switchover to the Gregorian calendar, ten days were dropped: October 15, 1582 is preceded by October 4 In the switchover to the Gregorian calendar, ten days were dropped: October 15, 1582 is preceded by October 4

20 Shlomo Hershkop 200720 Day Code public Day(int aYear, int aMonth, int aDate) public Day(int aYear, int aMonth, int aDate){ year = aYear; month = aMonth; date = aDate; } private int year; private int month; private int date; private static final int[] DAYS_PER_MONTH = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; private static final int GREGORIAN_START_YEAR = 1582; private static final int GREGORIAN_START_MONTH = 10; private static final int GREGORIAN_START_DAY = 15; private static final int JULIAN_END_DAY = 4; private static final int JANUARY = 1; private static final int FEBRUARY = 2; private static final int DECEMBER = 12;

21 Shlomo Hershkop 200721 Day Code private Day nextDay() 112: { 113: int y = year; 114: int m = month; 115: int d = date; 116: 117: if (y == GREGORIAN_START_YEAR 118: && m == GREGORIAN_START_MONTH 119: && d == JULIAN_END_DAY) 120: d = GREGORIAN_START_DAY; 121: else if (d < daysPerMonth(y, m)) 122: d++; 123: else 124: { 125: d = 1; 126: m++; 127: if (m > DECEMBER) 128: { 129: m = JANUARY; 130: y++; 131: if (y == 0) y++; 132: } 133: } 134: return new Day(y, m, d); 135: }

22 Shlomo Hershkop 200722 private static int daysPerMonth(int y, int m) { int days = DAYS_PER_MONTH[m - 1]; if (m == FEBRUARY && isLeapYear(y)) if (m == FEBRUARY && isLeapYear(y)) days++; days++; return days; return days;} private static boolean isLeapYear(int y) private static boolean isLeapYear(int y){ if (y % 4 != 0) return false; if (y < GREGORIAN_START_YEAR) return true; return (y % 100 != 0) || (y % 400 == 0); }

23 Shlomo Hershkop 200723 Tester 01: public class DayTester 02: { 03: public static void main(String[] args) 04: { 05: Day today = new Day(2001, 2, 3); //February 3, 2001 06: Day later = today.addDays(999); 07: System.out.println(later.getYear() 08: + "-" + later.getMonth() 09: + "-" + later.getDate()); 10: System.out.println(later.daysFrom(today)); // Prints 999 11: } 12: }

24 Shlomo Hershkop 200724 Notice Private helper methods Private helper methods Notice all the work to increment a day Notice all the work to increment a day

25 Shlomo Hershkop 200725 Another idea This is for illustration, don’t need to code This is for illustration, don’t need to code For greater efficiency, we can use Julian day number For greater efficiency, we can use Julian day number Used in astronomy Used in astronomy Number of days since Jan. 1, 4713 BCE Number of days since Jan. 1, 4713 BCE May 23, 1968 = Julian Day 2,440,000 May 23, 1968 = Julian Day 2,440,000 Greatly simplifies date arithmetic Greatly simplifies date arithmetic

26 Shlomo Hershkop 200726 Code public Day(int aYear, int aMonth, int aDate) { //notice we are calling a private //helper function julian = toJulian(aYear, aMonth, aDate); julian = toJulian(aYear, aMonth, aDate);} //that’s all we need private int julian;

27 Shlomo Hershkop 200727 Helper function private static int toJulian(int year, int month, int date) { int jy = year; if (year < 0) jy++; int jm = month; if (month > 2) jm++; else{jy--; jm += 13; } int jul = (int) (java.lang.Math.floor(365.25 * jy) + java.lang.Math.floor(30.6001 * jm) + date + 1720995.0); int IGREG = 15 + 31 * (10 + 12 * 1582); // Gregorian Calendar adopted Oct. 15, 1582 if (date + 31 * (month + 12 * year) >= IGREG) // Change over to Gregorian calendar { int ja = (int) (0.01 * jy); jul += 2 - ja + (int) (0.25 * ja); } return jul; }

28 Shlomo Hershkop 200728 Any other ideas? So you see that using the class doesn’t change even though we totally changed how the inside works So you see that using the class doesn’t change even though we totally changed how the inside works Called encapsulation Called encapsulation So its easy to move up or down the calendar So its easy to move up or down the calendar Add subtract Add subtract Where would it cost us ?? Where would it cost us ??

29 Shlomo Hershkop 200729 Switch gears Lets talk about how to use files Lets talk about how to use files Your program starts in main, computes, then maybe prints out something before closing up Your program starts in main, computes, then maybe prints out something before closing up Would be great if can save results somewhere Would be great if can save results somewhere Hey lets use files Hey lets use files

30 Shlomo Hershkop 200730 File manipulations Working with files Working with files Reading files Reading files Writing files Writing files

31 Shlomo Hershkop 200731 Please note One of the great things about file manipulation on java is that it is the same on One of the great things about file manipulation on java is that it is the same on Windows Windows Linux Linux Mac Mac If done right If done right

32 Shlomo Hershkop 200732 File Basic object is called File Basic object is called File File data = new File(“test.txt”); File data = new File(“test.txt”); It will look in the same directory the java file is sitting in for the test file It will look in the same directory the java file is sitting in for the test file Calling: data.getAbsolutePath() Calling: data.getAbsolutePath() Will print out the local version of the full path to the file Will print out the local version of the full path to the file

33 Shlomo Hershkop 200733 Directories If your File object is a directory If your File object is a directory The list method returns an array of String file names, The list method returns an array of String file names, listFiles returns an array of File objects listFiles returns an array of File objects

34 Shlomo Hershkop 200734 limitations The File object has a limited number of useful methods The File object has a limited number of useful methods None which can actually write something to it None which can actually write something to it Need to use higher level class to work with file contents Need to use higher level class to work with file contents

35 Shlomo Hershkop 200735 Dealing with text When dealing with text output/input can use When dealing with text output/input can use PrintWriter to write to a file PrintWriter to write to a file

36 Shlomo Hershkop 200736 code PrintWriter pw = new PrintWriter(new FileWriter(new File("Test.txt"))); PrintWriter pw = new PrintWriter(new FileWriter(new File("Test.txt"))); What is FileWriter ? What is FileWriter ? Lets pull up the API Lets pull up the API

37 Shlomo Hershkop 200737 Helper class to help make sure things are written efficiently Helper class to help make sure things are written efficiently Don’t forget to close the file handle when done Don’t forget to close the file handle when done And flush if using a buffered handle And flush if using a buffered handle

38 Shlomo Hershkop 200738 Ok lets write some code Ok lets write some code Main program Main program Will write a 3 line poem (yes you need to write one now) to a test.txt file Will write a 3 line poem (yes you need to write one now) to a test.txt file Notice how your have to add try catch to handle certain declared exceptions ?? Notice how your have to add try catch to handle certain declared exceptions ??

39 Shlomo Hershkop 200739 Run code Confirm that the file has been created Confirm that the file has been created Now write another class to read the file Now write another class to read the file

40 Shlomo Hershkop 200740 How would you adopt the reader to find something in the file ?? How would you adopt the reader to find something in the file ??

41 Shlomo Hershkop 200741 For each line read For each line read Look for something Look for something See String API for helper methods See String API for helper methods Now write the code Now write the code

42 Shlomo Hershkop 200742 Next up Interfaces Interfaces Inheritance Inheritance Abstract Classes Abstract Classes Polymorphism Polymorphism Generics Generics

43 Shlomo Hershkop 200743 Two dimensions You can also initialize the inner array as a separate call. You can also initialize the inner array as a separate call. Doesn’t have to be congruous memory locations Doesn’t have to be congruous memory locations int [][]example = new int[5][]; for (int i=0;i<5;i++){ example[i] = new int[i+1]; }

44 Shlomo Hershkop 200744 Interface An interface is a special class that defines the behavior of other classes An interface is a special class that defines the behavior of other classes Example Example How many mp3 players are on the market ? How many mp3 players are on the market ?

45 Shlomo Hershkop 200745 Mp3 players No matter what type of mp3 player you buy you expect certain behavior No matter what type of mp3 player you buy you expect certain behavior Play Play Forward(next song) Forward(next song) Rewind(last song) Rewind(last song) Random Random Think of your own Think of your own

46 Shlomo Hershkop 200746 If I want to program a bunch of mp3 players and want to force all of them to have some minimum behavior I would encode that as an interface If I want to program a bunch of mp3 players and want to force all of them to have some minimum behavior I would encode that as an interface Here is an example: Here is an example:

47 Shlomo Hershkop 200747 code public interface mp3player { public boolean play(); public boolean rewind(); public boolean forward(); public int getSongCount(); public boolean deleteAll(); }

48 Shlomo Hershkop 200748 analysis Basically am defining ideas Basically am defining ideas Would add comments to each what they are supposed to be doing (expected behavior Would add comments to each what they are supposed to be doing (expected behavior Then any class which wants to be nice, would agree to behave this way Then any class which wants to be nice, would agree to behave this way

49 Shlomo Hershkop 200749 Code: IpodMP3 Say we want to create a really cool mapple ipod player Say we want to create a really cool mapple ipod player Want to stick to the mp3 behavior Want to stick to the mp3 behavior public class Ipodmp3 implements mp3player {.. This means that we need to define those methods for this specific class This means that we need to define those methods for this specific class

50 Shlomo Hershkop 200750 Note Can implement as many interfaces as you like Can implement as many interfaces as you like Will notice them in the api when you look at the standard libraries Will notice them in the api when you look at the standard libraries Compiler will check and complain if you don’t implement all the methods you are promising in the interface you impliment Compiler will check and complain if you don’t implement all the methods you are promising in the interface you impliment Nothing actually checks that you are doing the correct thing….that is up to the programmer Nothing actually checks that you are doing the correct thing….that is up to the programmer

51 Shlomo Hershkop 200751 GASP! Question: so what does : Ipodmp3 player1 = new Ipodmp3 (); player1.play() actually do ?? Question: so what does : Ipodmp3 player1 = new Ipodmp3 (); player1.play() actually do ?? Answer: Maybe erase your hard drive…look at the source code Answer: Maybe erase your hard drive…look at the source code

52 Shlomo Hershkop 200752 Iterators Many of the classes in Java represent a collection of items Many of the classes in Java represent a collection of items Some have order Some have order Some don’t have order Some don’t have order All the students in one room All the students in one room Alphabetical list Alphabetical list Bag of names (raffle) Bag of names (raffle)

53 Shlomo Hershkop 200753 Two types Here is a general Iterator idea Here is a general Iterator idea Get the iterator object from the class Get the iterator object from the class Can ask the iterator object if it has any more stuff Can ask the iterator object if it has any more stuff Get the next thing Get the next thing

54 Shlomo Hershkop 200754 Inheritance You have a really useful class You have a really useful class Want to specialize it in more than one way Want to specialize it in more than one way Can either copy paste a bunch of time and tweak each copy Can either copy paste a bunch of time and tweak each copy Problem if we find a bug, will need to run to all copies and fix everything Problem if we find a bug, will need to run to all copies and fix everything

55 Shlomo Hershkop 200755 Easier way: Look at all the classes that are related, what ideas do they all share Look at all the classes that are related, what ideas do they all share Example: what is common between all kinds of cars Example: what is common between all kinds of cars Make that idea the base class, and each specialization a sub class Make that idea the base class, and each specialization a sub class Known as inheritance! Known as inheritance!

56 Shlomo Hershkop 200756 Inheritance Use the ‘extends’ keyword Use the ‘extends’ keyword Allows you to reuse objects Allows you to reuse objects Some issues: Some issues: When do you extend? When do you extend? When do you implement an interface? When do you implement an interface?

57 Shlomo Hershkop 200757 Example Geneal idea of an Animal Geneal idea of an Animal Can code it as class Animal Can code it as class Animal Then have specific code Then have specific code class Horse extends Animal class Horse extends Animal class Whale extends Animal class Whale extends Animal What ever methods are the same in both would be coded in the Animal class, specific methods (numberLegs() would be defined in the specific subclass) What ever methods are the same in both would be coded in the Animal class, specific methods (numberLegs() would be defined in the specific subclass)

58 Shlomo Hershkop 200758 Super constructors When refering to parent class (Animal) When refering to parent class (Animal) Use super keyword in subclass constructor: Use super keyword in subclass constructor: public Horse(String aName) public Horse(String aName) { super(aName); // calls superclass constructor super(aName); // calls superclass constructor //rest of your stuff here //rest of your stuff here } Call to super must be first statement in subclass constructor Call to super must be first statement in subclass constructor If subclass constructor doesn't call super, superclass must have constructor without parameters If subclass constructor doesn't call super, superclass must have constructor without parameters

59 Shlomo Hershkop 200759 Polymorphism This is just fancy word that tells you java will figure out the following code: This is just fancy word that tells you java will figure out the following code: Animal A = new Horse(“tom”); Animal A = new Horse(“tom”); So although A is really a horse, it can be refered to by parent handle. So although A is really a horse, it can be refered to by parent handle. This would be illigal: This would be illigal: Horse A = new Whale(); Horse A = new Whale(); Why ? Why ?

60 Shlomo Hershkop 200760 Next Imagine you have a class which has variable members of a specific type Imagine you have a class which has variable members of a specific type Example: Example: Have a list of numbers, say a list of zip codes which you have sent packages in the last X months Have a list of numbers, say a list of zip codes which you have sent packages in the last X months What if you want to change zip codes to Strings because you are now sending packages to canada What if you want to change zip codes to Strings because you are now sending packages to canada

61 Shlomo Hershkop 200761 2 solutions Copy paste code and replace all ints with Strings Copy paste code and replace all ints with Strings Debug like crazy Debug like crazy ….or use Generics ….or use Generics

62 Shlomo Hershkop 200762 Basic idea Tell java you are dealing with some type without know what it is Tell java you are dealing with some type without know what it is Can set some rules on it Can set some rules on it When you create an instance of the object you will tell java what you want When you create an instance of the object you will tell java what you want

63 Shlomo Hershkop 200763 Code public class shoppingList { private ArrayList theList; shoppingList(){ theList = new ArrayList (); } public void addItem(T item){ theList.add(item);} public int getNumberOnList(){ return theList.size(); } public T getItemAt(int location){ return theList.get(location); }}

64 Shlomo Hershkop 200764 Code 1 //once you get previous screen running at the following method public void showType() { System.out.println("Type of T is " + System.out.println("Type of T is " + ob.getClass().getName()); ob.getClass().getName());}

65 Shlomo Hershkop 200765 Usage shoppingList e1; e1 = new shoppingList ; e1.add(15); int v = e1.getItemAt(0); Write a main to test the idea of generics

66 Shlomo Hershkop 200766 Example2 class Example2 { T ob1; T ob1; V ob2; V ob2; Example2(T o1, V o2) { ob1 = o1; ob1 = o1; ob2 = o2; ob2 = o2; } T getob1() { return ob1; return ob1; } V getob2() { return ob2; return ob2; }}

67 Shlomo Hershkop 200767 Example 3 class Example3 { Q[] nums; // array of Number or subclass Stats(Q[] o) { nums = o; nums = o; } double sum() { double sum = 0.0; double sum = 0.0; for(int i=0; i < nums.length; i++) for(int i=0; i < nums.length; i++) sum += nums[i].doubleValue(); sum += nums[i].doubleValue(); return sum; return sum; }}

68 Shlomo Hershkop 200768 Usage Double dnums[] ={ 1.1, 2.2, 3.3, 4.4, 5.5 }; Example3 dob = new Example3 (dnums); double w = dob.sum(); System.out.println("dob sum is " + w);

69 Shlomo Hershkop 200769 Example4 class TwoD { int x, y; int x, y; TwoD(int a, int b) { TwoD(int a, int b) { x = a; x = a; y = b; y = b; }} class ThreeD extends TwoD { int z; int z; ThreeD(int a, int b, int c) { ThreeD(int a, int b, int c) { super(a, b); super(a, b); z = c; z = c; }} class FourD extends ThreeD { int t; int t; FourD(int a, int b, int c, int d) { FourD(int a, int b, int c, int d) { super(a, b, c); super(a, b, c); t = d; t = d; }}

70 Shlomo Hershkop 200770 class Coords { T[] coords; T[] coords; Coords(T[] o) { coords = o; } Coords(T[] o) { coords = o; }}

71 Shlomo Hershkop 200771 static void showXY(Coords c) { System.out.println("X Y Coordinates:"); System.out.println("X Y Coordinates:"); for(int i=0; i < c.coords.length; i++) for(int i=0; i < c.coords.length; i++) System.out.println(c.coords[i].x + " " + System.out.println(c.coords[i].x + " " + c.coords[i].y); c.coords[i].y); System.out.println(); System.out.println(); }

72 Shlomo Hershkop 200772 static void showXYZ(Coords c) { System.out.println("X Y Z Coordinates:"); System.out.println("X Y Z Coordinates:"); for(int i=0; i < c.coords.length; i++) for(int i=0; i < c.coords.length; i++) System.out.println(c.coords[i].x + " " + System.out.println(c.coords[i].x + " " + c.coords[i].y + " " + c.coords[i].y + " " + c.coords[i].z); c.coords[i].z); System.out.println(); System.out.println(); }

73 Shlomo Hershkop 200773 static void showAll(Coords c) { System.out.println("X Y Z T Coordinates:"); System.out.println("X Y Z T Coordinates:"); for(int i=0; i < c.coords.length; i++) for(int i=0; i < c.coords.length; i++) System.out.println(c.coords[i].x + " " + System.out.println(c.coords[i].x + " " + c.coords[i].y + " " + c.coords[i].y + " " + c.coords[i].z + " " + c.coords[i].z + " " + c.coords[i].t); c.coords[i].t); System.out.println(); System.out.println(); }

74 Shlomo Hershkop 200774 Using in methods Just learn how to read the following: Just learn how to read the following: static boolean isIn(T x, V[] y) { for(int i=0; i < y.length; i++) for(int i=0; i < y.length; i++) { if(x.equals(y[i])) return true; if(x.equals(y[i])) return true; } return false; return false;}

75 Shlomo Hershkop 200775 Hope you had fun learning this! Hope you had fun learning this!


Download ppt "Shlomo Hershkop 2007 1 Advanced Review. Shlomo Hershkop 20072 Advanced Review Time classes Time classes Date Classes Date Classes File input/output File."

Similar presentations


Ads by Google