04b: Recap
ICS211, Fall 2012
Dr. Zach
(switch view)
Status check
- Sound check
- Exam on Monday!
- Readings updated: focused, (optional), [done with]
- Should mention Towers of Hanoi (and in Ch. 5)
Discussion 01: Algorithm Selection Criteria
- Algorithm you know or can create
- Correctness (Accuracy) (~11+)
- Actually solves your problem
- Already implemented and debugged
- Reuse from API, from 3rd party library, from earlier project
- NOTE: not usually an option in this class though... :(
- Simplicity + Clarity (~7 + ~6 = ~13)
- Easy to implement
- Readable / understandable (for self; for team mates)
- Maintainable / changeable
- Can't always be simple, but can be clear
- Time efficiency / execution speed (~12)
- Growth rate (big-O)
- Context / end-user utility (~5)
- UI experience, etc.
- context of use
- system responsiveness: (hardware performance), cross-platform/device
- (program robustness/flexibility in face of bad input)
- Others...
- Memory usage (~1); data structure type or size you're working with (~2)
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)
- 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 A04 code)
- (backtracking)
The exam itself
- Spread out: a seat between each of you if possible
- Closed book, no notes
- Question types: short answer (1 multiple choice question)
- 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)
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
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)
- Every time you create an array or see the word
new
, something gets created in the heap
- Variables containing heap objects contain only a reference (memory address) to heap object
int[] evens = {2, 4, 6};
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.
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 (without 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;
}
}
Enums
(might be review)
Defining
- (Better) alternative to static final CONSTANTS when you have a related set of constants
- List all possible values (convention: in ALL_CAPS)
- enum is very much like a class (even in its own .java file)
- listed values are each an instance (object) of that class; cannot create any other new instances
public enum Suit {
SPADES, HEARTS, DIAMONDS, CLUBS;
}
public enum Direction {
N, NE, E, SE, S, SW, W, NW, HERE;
}
Example Use
// a constructor in class PlayingCard
public PlayingCard(int value, Suit suit) {
//...
}
PlayingCard card = new PlayingCard(4, Suit.CLUBS);
- No error checking needed for suit: can ONLY be one of the 4 suit values!
Other advantages
- Just as convenient as using int constants:
- can compare using == (ie:
if (dir == Direction.N)
)
- can use as switch case values
- but better:
- when printed, appear as NAME, not as some numerical value
- can have associated methods
- can even have internal state/instance variables (beyond our uses here)
Important methods
Every enum can has the following:
- a static
values()
method: returns an array of all values
Direction[] dirs = Direction.values();
for (Direction dir : dirs) {
System.out.print(dir + " "); //prints: N NE E SE S SW W NW HERE
}
System.out.println(dirs[1]); //print NE
- each instance has an
ordinal()
method: returns 0-based position in ordering
Direction dir = Direction.SE;
System.out.println(dir.ordinal()); //prints: 3
Before next time...
- A04 due tonight (or so)
- A05 (maze) posted later today... (will have longer than 1 week to do it, but 70? points)
- Quiz 4... (due Wed, after exam; first half might helpful review though)
- Exam 1 on Monday.