600.107 Intro to Java Review Session TA: Jai Madhok Email: jaimadhok@jhu.edu Chapter 7: User Defined Methods • Look up the common methods form the Math class, String class, Character class, Random class • How can Public static methods be called? className.methodName(parameters) • User defined methods: Value returning or Void • Void methods can be ‘stand-alone’ statements • Syntax of value returning methods Public/private static(or not) returnType name (Parameters) • • • • • • Method cannot return multiple values Void methods generally print/display stuff Is nesting of methods allowed? Static methods can be accessed only by static methods Know scope of identifiers within a class Method Overloading, know what this is and how can u implement this while writing classes? Can return types of overloaded methods be different? • Know how to work with random objects • Sample Problem on Chapter 7 (Difficulty level: Easy) Write a method that can be used by other users in their classes to check if an alphanumeric code is a palindrome or not. The method must take in the code and its length as parameters. (You may assume that the code doesn’t have spaces in between) Chapter 8: User Defined Classes • Encapsulation: combining data with operations on the data– Core of OOP • An object combines data and operations on the data • Instance Variables are the non static data members of the class • Do not use public instance variables on the exam while writing classes unless the question demands it. • Constructors execute when an object of the class is created. Special methods with no Return type (NOT VOID) • Constructors can be overloaded, they must have different signatures • Shallow copying Vs Deep Copying of data. • Don’t worry too much about the technicality just the how to implement the stuff • Accessor Vs Mutator methods: get Vs set • Using the ‘.’ member access operator to refer to instance variables. • toString is inherited and prints the class name and the hash code of the object by default • You need to ‘over ride’ this method. Different from overloading • The implicit reference ‘this’ Using a Static Variable as a counter in a class • Why would you use a static data member? - As ID for object - To keep track of how many objects have been instantiated so far - Know that static data members are common to all the objects in the class Chapter 9: Array Manipulation • General Syntax: • • • • • • dataType[] or [][] name = new dataType[size] or [m][n] arrayName.length gives the length of the array Array indexing begins from 0 What is the ArrayIndexOutOfBoundsException? In case of a 2D array arrayName[0].length gives the number of columns in the 2D grid assuming it’s an uniform grid Can have arrays of user defined objects. Ex: Array of ‘Boats’ know to write methods to compare, copy and find elements in an array using simple for loops Example: Equal Arrays? public static boolean isEqual(int[ ] list1, int[ ] list2) { int len1= list1.length; int len2= list2.length; if (len1!=len2) return false; for(int a=0; a<len1;a++) if(list1[a]!=list2[a]) return false; return true; } Chapter 10: Applications of Arrays • Typical questions are the ones where you have to tell what an array looks like in the ith iteration of the for loop involved in the code • So you need to know what happens at each step in sorting/searching • Algorithms you need to know: Bubble sort, insertion sort, merge sort (recursive), linear search, binary search Simple Sorting Algorithms 0(N2) • O(N2) sorting algorithms. • In bubble sort, a next position to fill is compared with all later positions, swapping out-of-order values. • In selection sort, the smallest value in the remaining positions is computed and swapped with the value in the next position. • In insertion sort, the next value is moved backward (swapped with the value in the previous position in the region of sorted values) until it reaches its correct position. Complex Sorting Algorithms 0(Nlog2N) • Merge Sort, heap sort, quick sort • Just look at the code, you will NOT be expected to write code that implements these algorithms Binary Search on a sorted list only!! • O(log N) • Done using a recursive algorithm • Efficient Chapter 11: Inheritance and Polymorphism • Inheritance – ‘is-an’ relationship • A sub-class ‘ extends’ the definition of a super class • Private members of the super class cannot be accessed directly by the sub class • Sub class can override methods of the super • All data members of the super class are members of the sub class as well • Multiple inheritance is NOT allowed in java • Use super and ‘.’ to access overridden methods of the super class • Protected members of the super class can be accessed by the sub class • A constructor of a sub class cannot initialize the data members of the super class • Needs to call the constructor of the super class with the reserve word super • The instanceOf operator is used to determine if an object is an instance of a particular class type Class Object • Indirectly the super class of every class in Java • Important Method that you NEED to know how to over write is: public boolean equals(Object obj) Comparable Interface • Any class that implements this interface should override the method public int compareTo (Object o) The next slide has an example of how this method should be written correctly. The practice tests posted online also have an example. • Say you were doing this for the Waiter class public int compareTo(Object o) { //check if o is a Waiter to begin with if(o instanceof Waiter) { //Begin by typecasting ‘o’ to a Waiter //Do the appropriate computation to determine which Waiter wins the comparison } else {//Handle appropriately depending on program specifications} } Chapter 12: Exceptions • Idea of an exceptional event, what do when such an event occurs • Try catch finally blocks • Throw and throws • Throwable class and its sub classes • Kinds of Exceptions (Just the basic types) Chapter 14: Recursion • Base cases must be defined appropriately in order to prevent infinite recursion • Direct Vs indirect Examples Assume that the following declaration has been made at the beginning of the main class declaration: static random rand= new Random(); a. Assuming that ch1 and ch2 are initialized character variables, with ch1<=ch2 and both uppercase, write a statement to put a character between ch1 and ch2(inclusive) into a third variable ch3. [6 points] b. Write the header of a method that could appear in a main driver program which has 2 character parameters and returns a random upper case letter between those values [3 points] c. Write a recursive statement that could be added to the definition of the above method in order to handle the case where the first actual parameter comes later in the alphabet than the second one. You can still assume they are both uppercase. [3 points] d. Write javadocs for the method above [5 points] Potential Types of Questions • Recursive Method writing (can be hard) • Tracing through a chunk of code where in a recursive method is called several times. The method definition will be given to you • Code tracing with arrays • Writing methods, java docs and appropriate method calls for them, don’t take this lightly. • Completing class definition using the comments and hints given • Writing syntactically correct statements to get some specific output from the class definition you completed just as in the sample practice exams • Questions on inheritance, maybe writing a sub-class for a given super class • Valid/ invalid statements • True/false • Fill in the blanks • Multiple choice • Other surprise stuff General Stuff • Be careful, especially in the multiple choice questions • Read the summaries of the chapters in the text book • Shoot me an email if you have any questions. I will respond until midnight today within a short time • Do the reviews posted on the website under exam conditions • Write down stuff for partial credit in case of code tracing type of questions • Further questions: Email me at jaimadhok@gmail.com • Good Luck! public static String vowels(int len) { String v=“AEIOU”; String makeV=””; for(int i=0;i<len;i++) makeV+=v.charAt(rand.nextInt(5)); return makeV; } /** Generate a random string of vowels of a desired length @param len is the integer length… @return is the random string generated */ System.out.println(vowels(8)); • Public PhoneEntry(String n, long c) { name=n; cell=c; entries++; } Public String getEntry() { return name; } Public static int getEntries() { return entries; } System.out.println(PhoneEntry.getEntries()); PhoneEntry myself= new PhoneEntry(“jai”,234321432); System.out.println(pe.getName())’ PhoneEntry[] cellphone=new PhoneEntry[65]; Cellphone[0]=myself; public int compareTo (Object o); Implements Comparable next to the class header Public boolean equals(Object o) { If(! O instanceof PhoneEntry) { System.out.println(“ERROR!!”); System.exit(0); } PhoneEntry newP= (PhoneEntry) o; If(this.name.equalsIgnoreCase(newP.name)) If(this.cell==newP.cell) Return true; Public int compareTo(Object obj) { If(! Obj instanceof Car) { } Car c= (Car) obj; } Public String toString() { Return super.toString() + fagewgewgewgew; }