Shlomo Hershkop Advanced Review
Shlomo Hershkop Advanced Review Time classes Time classes Date Classes Date Classes File input/output File input/output Packages Packages
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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)
Shlomo Hershkop 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?
Shlomo Hershkop 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() ??
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop Relationships
Shlomo Hershkop 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
Shlomo Hershkop 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 _____________)
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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;
Shlomo Hershkop 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: }
Shlomo Hershkop 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); }
Shlomo Hershkop Tester 01: public class DayTester 02: { 03: public static void main(String[] args) 04: { 05: Day today = new Day(2001, 2, 3); //February 3, : 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 : } 12: }
Shlomo Hershkop Notice Private helper methods Private helper methods Notice all the work to increment a day Notice all the work to increment a day
Shlomo Hershkop 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
Shlomo Hershkop 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;
Shlomo Hershkop 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( * jy) + java.lang.Math.floor( * jm) + date ); int IGREG = * ( * 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; }
Shlomo Hershkop 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 ??
Shlomo Hershkop 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
Shlomo Hershkop File manipulations Working with files Working with files Reading files Reading files Writing files Writing files
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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 ??
Shlomo Hershkop 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
Shlomo Hershkop How would you adopt the reader to find something in the file ?? How would you adopt the reader to find something in the file ??
Shlomo Hershkop 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
Shlomo Hershkop Next up Interfaces Interfaces Inheritance Inheritance Abstract Classes Abstract Classes Polymorphism Polymorphism Generics Generics
Shlomo Hershkop 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]; }
Shlomo Hershkop 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 ?
Shlomo Hershkop 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
Shlomo Hershkop 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:
Shlomo Hershkop code public interface mp3player { public boolean play(); public boolean rewind(); public boolean forward(); public int getSongCount(); public boolean deleteAll(); }
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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)
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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!
Shlomo Hershkop 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?
Shlomo Hershkop 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)
Shlomo Hershkop 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
Shlomo Hershkop 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 ?
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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
Shlomo Hershkop 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); }}
Shlomo Hershkop 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());}
Shlomo Hershkop Usage shoppingList e1; e1 = new shoppingList ; e1.add(15); int v = e1.getItemAt(0); Write a main to test the idea of generics
Shlomo Hershkop 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; }}
Shlomo Hershkop 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; }}
Shlomo Hershkop 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);
Shlomo Hershkop 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; }}
Shlomo Hershkop class Coords { T[] coords; T[] coords; Coords(T[] o) { coords = o; } Coords(T[] o) { coords = o; }}
Shlomo Hershkop 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(); }
Shlomo Hershkop 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(); }
Shlomo Hershkop 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(); }
Shlomo Hershkop 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;}
Shlomo Hershkop Hope you had fun learning this! Hope you had fun learning this!