04b: Recap
ICS211, Spring 2013
Dr. Zach
(switch view)
Status check
- Exam on Monday!
- First EC1 (CodingBat) scoring will occur a couple days after that
- Make sure you share your account with me and your TA, if you haven't already
Parallels
- Every problem has more than one algorithm to solve it, and more than one possible implementation of each algorithm
- Software development process walks you through those same steps: clarifiying some vague/abstract problems, making a plan, and then writing a specific program to solve the problem
- Design involves more than just selecting algorithms (UI design, division of code into methods/classes/packages, etc)
Discussion 01: Algorithm Selection Criteria
- Algorithm you know and understand / or can design / can code (ability)
- Appropriate: actually solves your problem?
- may want challenge on one you don't know (well)
- Correctness (accuracy / consistency / precision / certainty / no crashes)
- Robustness / flexibility (range of situations)
- Already implemented and debugged (!)
- Reuse from API, from 3rd party library, from earlier project
- NOTE: often not an option in this class though... :(
- Simplicity + Clarity
- Easy to understand
- Easy to implement.
- Resulting code is:
- Readable / understandable (for self; for team mates)
- Maintainable / changeable
- Can't always be simple, but can be clear
- Time efficiency / execution speed
- But how much faster than alternative? Worth the extra effort?
- May vary based on nature of data
- Sorting itself is an overhead: worth it?
- Growth rate (big-O)
- algA better on small data set, algB better on large
- Context / end-user utility
- (This is more a feature of programs, not algorithms, but part of context...)
- UI experience, etc.
- context of use
- system responsiveness: (hardware performance), cross-platform/device
- (program robustness/flexibility in face of bad input)
- Others...
- Memory usage
- Data structure type or size you're working with
- Reusable in other contexts after implementation
Discussion 01: Conclusions
- Right algorithm depends on context of use!
- Just like our directions and recipe examples
- Don't get obsessed with speed/efficiency, or big-O, or any single factor
- Consider all of your needs
Java Review
Odds and Ends
Arrays: Useful Tricks
int[] nums = {1, 2, 3, 4};
nums = {2, 4, 6, 8}; // NO! Can only initialize this way
nums = new int[]{2, 4, 6, 8}; // works
java.util.Arrays has many useful methods, including copyOf, equals, and toString.
String asStr = java.util.Arrays.toString(nums);
System.out.println(asStr); //prints: [2, 4, 6, 8]
System.out.println(java.util.Arrays.toString(new int[]{5, 8, 13, 21}));
Some people also like System.arraycopy
method. (Very versatile. Check out the API.)
Arrays and the Heap (1/2)
int[] evens = {2, 4, 6}; //implicitly invoking new
int[] odds = {1, 3, 5};
odds = evens;
odds[1] = 7;
System.out.println(evens[1]);
What does this print?
Arrays and the Heap (2/2)
public class Example {
public static void main(String[] args) {
int[] nums = {1, 3, 5, 8};
int a = 1;
int b = 2;
swap(nums, a, b);
System.out.println("nums[a] = " + nums[a] + ", nums[b] = " + nums[b]);
}
public static void swap(int[] array, int left, int right) {
int temp = array[left];
array[left] = array[right];
array[right] = temp;
}
}
- What does this print? Did the swap work?
- Compare to slide 02A#23
Wrapper classes
- Java is OO, so sometimes you need to send a primitive to a method that will only take objects
- Wrapper classes!
- name = primitive name with capital first letter: Double, Boolean, Float, etc.
- except: Integer (for int), Character (for char)
- in java.lang (no import needed)
- Since Java 5, compiler will automatically wrap (autobox) and unwrap (auto-unbox) for you
Wrapper classes: Autoboxing example
//old manual way
int num = 5;
Integer number = new Integer(num); //wrapping up value
//...could now pass number to some method that only takes an object
int x = number.intValue() //unwrapping
//now, with autoboxing
Integer five = num; //autobox: assign int to Integer and it worked!
Integer f = 5; //same
int n = five; //unboxing: assigned Integer value to int
- Still overhead to this, so don't use wrappers unless you need to
- Wrapper classes also have a few useful methods too (like Integer.parseInt, etc).
- See Appendix A.5, Tutorial, or API for more.
java.util.ArrayList
- An object with an array inside that grows as needed
- Should always specify data type of contents using <generics>
- If holding primitives, need to use wrapper class names: Integer, Character, Double, Float, ...
- Need to use methods to manipulate (see API for full details)
java.util.ArrayList<Integer> nums = new java.util.ArrayList<Integer>();
nums.add(3); //autoboxing at work
nums.add(6);
nums.add(1, 4);
int x = nums.get(0); //x == 3
nums.set(2, 5); //changes 6 to 5
System.out.println(nums); //prints: [3, 4, 5]
System.out.println("size=" + nums.size()); //prints: size=3
Footnote: Later in the term we'll learn why it's better to use
List<Integer> nums = new ArrayList<Integer>();
here and to write methods to take and return List rather than ArrayList.
Exam 1
What to expect
What we've learned so far...
"Let me explain... No, there is too much. Let me sum up."
--Inigo Montoya, The Princess Bride
What you should know for the exam... Java
- Procedural Java
- variables -- data types, declaration, initialization, assignment
- operators -- precedence
- conditionals -- if, else, switch
- loops -- while, for (both versions), (do-while), break, (continue)
- arrays -- creating, processing/changing, multi-dimensional
- catching exceptions -- try, catch, (finally)
- methods -- parameters, local variables, signatures, overloading
- command line args, (file IO, ArrayList)
- Know how to both read, write, and recognize all these
What you should know for the exam... concepts
- Algorithms -- what are they? how do you select one?
- big-O
- what is it? what does it measure? limitations? vs benchmarking
- determine the big-O of a method or section of code
- common big-Os and their relative ordering: O(1), O(n), O(n^2), O(n^3), O(2^n), etc
What you should know for the exam... processes
- Software development process
- models -- waterfall, spiral, agile programming; basic similarities + differences
- common steps -- requirements, design, implementation, testing, maintenance
- Recursion
- what is it? how does it work?
- parts and terms: base case, recursive call; vs. iterative
- recognize, read/trace, and write as code
- big-O of simple examples (like A03 code)
- (backtracking)
The exam itself
- Spread out: a seat between each of you (as much as possible)
- Closed book, no notes
- Question types: short answer (1 multiple choice question)
- read (trace) code and tell me what it prints
- write a short method or piece of code (recursive or iterative)
- recognize concepts in code (big-O, variable declarations, etc)
- concepts (algorithms, software development)
- Show your work/reasoning when you can (partial credit)
Looking ahead...
- Review OOP (object-oriented programming)
- Learn new OOP and Java tricks
- Abstract Data Types
- evaluate and compare algorithms (big-O)
- practice and use recursion
Java Review
Objects
Classes
- As program (main method), as collection of static methods, or as template for building objects.
- Simplest class:
public class Simple {
}
- If you don't write a constructor, compiler provides a default one that takes no parameters and does nothing, so:
public static void main(String[] args) {
Simple s = new Simple();
}
Like arrays, objects are in the heap.
Object state = Instance variables
public class Cat {
String name;
int lives;
}
- How do you recognize an instance variable?
- Declared (in a class but) outside of any method
- No
static
keyword
Constructor
- Makes it easier to build the object
- Lets you prevent objects with illegal state
public class Cat {
String name;
int lives;
public Cat(String name, int lives) {
this.name = name;
this.lives = (lives < 1) ? 1 : lives;
}
}
- How do you recognize a constructor?
Like a method but: 1) Same name as class 2) No return type
this
this
keyword refers to the current object of this class
- always preface instance variables with
this.
when you refer to them
- (Java will prepend
this.
if there is no local variable or parameter with that name)
public class Cat {
String name;
int lives;
//preferred version
public Cat(String name, int lives) {
this.name = name;
this.lives = (lives < 1) ? 1 : lives;
}
//alt: works (but is not as good)
public Cat(String n, int l) {
name = n;
lives = (l < 1) ? 1 : l; //Tip: NEVER use l as a variable name!
}
//alt: broken!
public Cat(String name, int lives) {
name = name;
lives = (lives < 1) ? 1 : lives;
}
}
Overloading constructors
- Convenient: client of your class doesn't need to specify common default values
- Not too tedious to write because you can call one constructor from another
public class Cat {
String name;
int lives;
public Cat(String name, int lives) {
this.name = name;
this.lives = (lives < 1) ? 1 : lives;
}
public Cat(String name) {
this(name, 9); //invoke other constructor rather than repeat code here
}
}
Object Behavior = Instance Methods
- Instance method == not
static
- Must be called on an object (instance) of the class; has access to that object's state
public class Cat {
String name;
int lives;
//(constructors omitted)
public void die() {
this.lives--;
}
public boolean isReallyDead() {
return lives <= 0;
}
}
Encapsulation: Good practice
- Make your instance variables private
- Read access: get method (accessor / "getter")
- Write access: set method (mutator / "setter")
public class Cat {
private String name;
private int lives;
public Cat(String name, int lives) {
this.name = name;
this.lives = (lives < 1) ? 1 : lives;
}
public String getName() {
return this.name;
}
public void setName(String name) { //can rename a cat?
this.name = name;
}
public int getLives() {
return this.lives;
}
}
Summary
- How to pick an algorithm
- Java odds and ends: arrays in the heap, wrapper classes, ArrayList
- What to expect on the exam
- Started OOP review: instance variables, constructors, instance methods, encapsulation
Before next time...
- A03 due soon
- A04 (maze) posted
- Quiz 4 due before exam
- Exam 1 on Monday.