Title: CS 9G Java Final Review
1CS 9G Java Final Review
- Welcome! My name is Jonathan Tsai
- Monday, December 13, 2004
- About 24 hours left until final
- Hope you enjoy the review session
- Slides will be available online at
- PowerPoint
- http//www.ocf.berkeley.edu/jontsai/files/cs9g_fi
nal_review.ppt - PDF
- http//www.ocf.berkeley.edu/jontsai/files/cs9g_fi
nal_review.pdf
1
2CS 9G Java Final Review
- CS 9G Final (You should have already signed up)
- Tuesday, December 14
- 8-11am, 1230-330 or 5-8pm. All in the Bechtel
Auditorium - For updated info check http//www-inst.eecs.berke
ley.edu/selfpace - Worth 40 of your grade
- Need about 70 in class to pass (I'm not sure
about this exactly)
2
3CS 9G Java Final Review
- What to expect on the final
- Big ideas in Java, topics indicated in the
following slides - Knowing exact parameters and names of functions
in obscure methods that are rarely used is not
important - But having the proper syntax is
- Partial credit will be given for small errors
- Okay, ready? Let's go!
- If I go to fast, feel free to stop me and ask
questions
3
4CS 9G Java Final Review
- Programming Assignments
- Applet Introduction Adding Machine
- Objects and Classes Cat and Mouse
- List Structures Butterfly
- Exception Handling Inventory
- Threads Bear
- Additional Topics
- Basic Java
- Object-oriented programming
- Data Structures
- Exceptions and Applications
4
5CS 9G Java Final Review
- Programming Assignments
- Applet Introduction Adding Machine
- Objects and Classes Cat and Mouse
- List Structures Butterfly
- Exception Handling Inventory
- Threads Bear
- Additional Topics
- Basic Java
- Object-oriented programming
- Data Structures
- Exceptions and Applications
5
6Adding Machine
- Applet
- import java.applet.Applet
- public void init ( )
- public void paint (Graphics)
- Widgets
- TextField
- Button
- Other
- public void actionPerformed(Event)
6
7Adding Machine
- Applet
- import java.applet.Applet
- public void init ( )
- public void paint (Graphics)
- Widgets
- TextField
- Button
- Other
- public void actionPerformed(Event)
7
8Adding Machine
- public void init( )
- Called whenever starting an applet
- HTML code
- ltapplet codeAddingMachine.class width300
height200gtlt/appletgt - Set up objects
- If have additional parameters to retrieve from
HTML code to Applet - Inside ltapplet ...gt and lt/appletgt, for each
parameter put - ltparam name"your_param_name" value"your_value"gt
8
9Adding Machine
- Applet
- import java.applet.Applet
- public void init ( )
- public void paint (Graphics)
- Widgets
- TextField
- Button
- Other
- public void actionPerformed(Event)
9
10Adding Machine
- public void paint(Graphics)
- Usually called by the applet whenever repaint( )
is called - Graphics object to be painted on must be passed
in as a parameter - Some Graphics method calls, given a Graphics
object g - g.drawString(Hello World)
- g.drawRect(0, 0, 50, 50)
10
11Adding Machine
- Applet
- import java.applet.Applet
- public void init ( )
- public void paint (Graphics)
- Widgets
- TextField
- Button
- Other
- public void actionPerformed(Event)
11
12Adding Machine
- Widgets
- import java.awt.
- import java.awt.event.
- Initialize it
- Button reset new Button(reset)
- Add it to the applet
- add(reset)
- Bind it with the actionListener
- reset.addActionListener(this)
- this refers to the current Applet
12
13Adding Machine
- Applet
- import java.applet.Applet
- public void init ( )
- public void paint (Graphics)
- Widgets
- TextField
- Button
- Other
- public void actionPerformed(Event)
13
14Adding Machine
- public void actionPerformed(Event)
- Determine the source of the Event e
- e.getSource( )
- Returns an object which corresponded to the call
from the previous slide - reset.addActionListener(this)
- Do some action
- Usually call repaint( ) as well
14
15CS 9G Java Final Review
- Programming Assignments
- Applet Introduction Adding Machine
- Objects and Classes Cat and Mouse
- List Structures Butterfly
- Exception Handling Inventory
- Threads Bear
- Additional Topics
- Basic Java
- Object-oriented programming
- Data Structures
- Exceptions and Applications
15
16Cat and Mouse
16
17Cat and Mouse
- Four Classes
- CatMouseChase.java
- Cat.java
- Mouse.java
- Position.java
- CatMouseChase was the Applet that controlled
display and mouse interaction, etc
17
18Cat and Mouse
- Cat and Mouse represented the cat and mouse,
respectively - Each has a private field, Position, which
represents the polar coordinates of the cat or
mouse with respect to the base - Create or instantiate a new object by calling the
constructor - Cat cat new Cat( )
18
19Cat and Mouse
- Use public accessor functions to retrieve the
private fields - Position catPos cat.getPosition( )
- Call public methods like so
- cat.move(0, 1)
- catPos.toString()
19
20CS 9G Java Final Review
- Programming Assignments
- Applet Introduction Adding Machine
- Objects and Classes Cat and Mouse
- List Structures Butterfly
- Exception Handling Inventory
- Threads Bear
- Additional Topics
- Basic Java
- Object-oriented programming
- Data Structures
- Exceptions and Applications
20
21Butterfly
- The classes
- ButterflyApplet
- ButterflyCollection
- Contains a data structure which holds butterflies
- Buttefly
- ButterflyDisplayer (for the thread, more on this
later) - Three versions
- Arrays
- Vector or LinkedList (using Java API)
- API Application Programming Interface
- Explicitly linked list (you made your own)
21
22Butterfly
- What was the point of this exercise?
- We hoped that you could see how you can implement
your own data structure, such as a
ButterflyCollection, that maintained a layer of
abstraction between the applet/displayer and the
actual butterflies being drawn - Can use generic methods like add(Butterfly),
remove(Butterfly), etc.
22
23Butterfly
- Implementing new data structures happens in real
life all the time - Usually performs specific additional features, or
to optimize time/space - Keep student records sorted by SID
- It's meaning is as simple as the name
- Something that holds data
- Can you think of data structures in real life (or
Java) that is based on simpler data structures?
23
24CS 9G Java Final Review
- Programming Assignments
- Applet Introduction Adding Machine
- Objects and Classes Cat and Mouse
- List Structures Butterfly
- Exception Handling Inventory
- Threads Bear
- Additional Topics
- Basic Java
- Object-oriented programming
- Data Structures
- Exceptions and Applications
24
25Inventory
- The classes
- InventoryTest
- Instantiated a new Inventory object, and
attempted to fill it - Inventory
- Underlying data structure array of entries
- Entry
- The name of the item
- How many there are
- LineFormatException
- The different errors that occur in a badly
formatted input file
25
26Inventory
- Let's examine some class and method signatures
- public Entry (String s) throws LineFormatException
- Yup, that's a constructor
- They can also support the throws keyword, just
like any other method - This simply means Calling this method can
potentially cause this error (specifically, a
LineFormatException). - class LineFormatException extends Exception
- LineFormatException is a subclass of Exception
- This is a concept of inheritance, we'll get to
that in a few slides
26
27Inventory
- When something bad happens, we'd like to throw an
exception - if (something_bad_happens)
- throw new LineFormatException(this is bad)
-
- Note that you don't just throw Exception, you
have to throw new Exception - Exceptions are just like any other object
27
28Inventory
- But don't fret! We have a safety net, which is
part of the idea of exception handling - try
- somethingBadMightHappen( )
- catch (LineFormatException e)
- // Display a message
- catch (Exception e)
- // this is in case an exception we didn't expect
is thrown - // consider it a safety net for the safety net
- // usually don't need to be this cautious
28
29Inventory
- So what's the deal with throws?
- We use this in a method signature to indicate
that some caller to this method must implement
try/catch, whether a direct caller or not - Otherwise, the program will crash when the
exception is encountered - Example
- public void somethingBadMightHappen( ) throws
LineFormatException - throw new LineFormatException(just
because)
29
30CS 9G Java Final Review
- Programming Assignments
- Applet Introduction Adding Machine
- Objects and Classes Cat and Mouse
- List Structures Butterfly
- Exception Handling Inventory
- Threads Bear
- Additional Topics
- Basic Java
- Object-oriented programming
- Data Structures
- Exceptions and Applications
30
31Bear
31
32Bear
- Depending how you implemented it, you might have
4 classes (similar structure to Butterfly
program) - An applet
- Something that extends Frame
- A displayer
- The Bear
- We'll focus on the thread and application aspects
of this program
32
33Bear
- A simple definition of an applet
- extends Applet
- has an init( ) method
- And an application
- has a main method
- Since we also want to have graphics displayed in
a window, our application must also extend Frame - This does not mean all applications have to
extend Frame - Inventory was an application that did not
33
34Bear
- Simple way to do it
- Put a main( ) method inside the applet that
instantiated the class that extends Frame (we'll
call it BearFrame) - BearFrame has to also implements WindowListener,
MouseListener - We'll talk about interfaces and implements later
34
35Bear
- The thread aspect of the program
- So what?
- Computers and computer programs that we use
commonly use don't really do multi-tasking
(thought it seems that way) - True multi-tasking would require a separate CPU
for each process - But, computers can achieve something to this
effect by running multiple processes for a short
interval at a time, and switching between them
extremely rapidly - These are called threads
35
36Bear
- How do I make a thread, say BearDisplayer?
- class BearDisplayer extends Thread
- public void run( )
- // This method is called by the program
when - // BearDisplayer.start( ) is called
-
-
- When do I use synchronized?
- Usually if the method is called inside the run(
), or is part of a resulting call by a method
invoked in run( ) - Don't worry too much about the specifics, you'll
learn more about this if you continue with CS
36
37CS 9G Java Final Review
- Programming Assignments
- Applet Introduction Adding Machine
- Objects and Classes Cat and Mouse
- List Structures Butterfly
- Exception Handling Inventory
- Threads Bear
- Additional Topics
- Basic Java
- Object-oriented programming
- Data Structures
- Exceptions and Applications
37
38Basics
- Naming convention
- Variables and Methods
- startWithLowerCase
- Initial letters of different words upper case in
multi-word variable or method name - If variable is final, all capitals, with
underscore between words - THIS_IS_A_CONSTANT
- Classes
- ThisIsAClass
- Like variable, first letter is upper-cased
38
39Basics
- Declare a variable
- int n
- Or many at a time int a, b, c, d
- Initialize a variable
- n 5
- Declare and initialize at same time
- int n 5
- int vars are initialized to 0 by default
- boolean to false
- But you shouldn't depend on this!
- If something is declare as final, you can't
reassign it (constants like Math.PI)
39
40Basics
- Integer division
- int i 5
- i 5 / 2
- System.out.println(i)
- What gets printed out?
40
41Basics
- Only one public class per file
- I'll write a sample class module to demonstrate
this - Sorry for the spacing/indenting!
- File FinalExamReview.java
- public class FinalExamReview // note the name
- public FinalExamReview( ) // default
constructor - public void setName(String n) myName n
- public String getName( ) return myName
- public String toString( ) return myName
- public boolean equals(Object o) return
false - private String myName
41
42Basics
- Make a new FinalExamReview object
- FinalExamReview rev new FinalExamReview( )
- Do some stuff
- rev.setName(cs9g)
- System.out.println(rev)
- In the last example, rev is not a String, but
it's toString method will be called by println to
get it's String representation
42
43Basics
- Decisions if and switch
- if (just like C)
- if (something)
- else
-
- Can be nested
- if (something)
- else
- if (something_else)
- else
-
43
44Basics
- This block of statements
- if (something)
- else
- if (something_else)
- else
-
-
- Is equivalent to
- if (something)
- else if (something_else)
- else
44
45Basics
- Switch
- // generate a random integer between 0 and 10
- int n Math.random( ) 11
- String s
- switch (n)
- case 0
- s zero break // exit the switch
statement - case 1
- s one break
- default // if it did not match any previous case
- s greater than one // don't need break
statement
45
46Basics
- Self test convert this code to not use switch
- // generate a random integer between 0 and 10
- int n Math.random( ) 11
- String s
- switch (n)
- case 0
- s zero break // exit the switch
statement - case 1
- s one break
- default // if it did not match any previous case
- s greater than one // don't need break
statement
46
47Basics
- For loop
- for (int i0 i lt array.length i)
- // Do something
-
- While loop
- while (somethingIsTrue)
- // Do something
47
48CS 9G Java Final Review
- Programming Assignments
- Applet Introduction Adding Machine
- Objects and Classes Cat and Mouse
- List Structures Butterfly
- Exception Handling Inventory
- Threads Bear
- Additional Topics
- Basic Java
- Object-oriented programming
- Data Structures
- Exceptions and Applications
48
49Object Oriented Programming
- Why is OOP so cool?
- Reusable code
- How real world works (at least a good model of
it) - Public
- Private
- Static
- Inheritance
- Interfaces
49
50Object Oriented Programming
-
- Pronounced equals-equals (I do, at least)
- For objects
- Returns true if they are in the same memory
location - False otherwise
- For primitives like int, boolean
- Returns true if they have the same value
- False otherwise
50
51Object Oriented Programming
- public boolean equals(Object o)
- Pronounced dot equals (I do)
- If a class does not have one specified, the one
that is implemented in Object will be used (since
all classes extend Object implicitly) - Note that it takes an Object as argument
- Can use instanceof operator
- I don't think you learned this but here's how
- if (o instanceof Butterfly)
- // o is indeed a Butterfly, cast it and use
it - else
- return false
51
52Object Oriented Programming
- public String toString( )
- Returns the string representation of an object
- If a class does not have one specified, the one
that is implemented in Object will be used (since
all classes extend Object implicitly), like
equals - Objects that are equals( ) to each other should
have the same toString( ) representation
52
53Object Oriented Programming
- Why is OOP so cool?
- Reusable code
- How real world works (at least a good model of
it) - Public
- Private
- Static
- Inheritance
- Interfaces
53
54Object Oriented Programming
- Most methods are declared public
- Instance fields use with care!
- Usually only for constants
- Any method in any class will have access to it
- If the class was BankAccount and the field was
balance, this would be highly undesirable for the
bank (or highly desirable for you)
54
55Object Oriented Programming
- Why is OOP so cool?
- Reusable code
- How real world works (at least a good model of
it) - Public
- Private
- Static
- Inheritance
- Interfaces
55
56Object Oriented Programming
- Most instance fields are declared private
- Void methods, usually
- Methods of the same class can access these
- Note! This is not the same as saying that private
fields are inaccessible from different objects
(not to each other)
56
57Object Oriented Programming
- Why is OOP so cool?
- Reusable code
- How real world works (at least a good model of
it) - Public
- Private
- Static
- Inheritance
- Interfaces
57
58Object Oriented Programming
- Static means that there is only one copy of a
method or field shared by all instances of that
class - Think of how one would keep track of the number
of instances of a class ever created - Static field numInstances will do
- How to invoke a static method
- ClassName.methodName(args)
- How to reference a static field
- ClassName.fieldName
- Public and private still apply
58
59Object Oriented Programming
- Why is OOP so cool?
- Reusable code
- How real world works (at least a good model of
it) - Public
- Private
- Static
- Inheritance
- Interfaces
59
60Object Oriented Programming
- Any class can only extend one class (no multiple
inheritance like C) - Protected
- Protected fields can be accessible in subclasses,
but not by methods of classes outside of the
inheritance hierarchy - Cannot be protected and private
- Private fields are not inherited
60
61Object Oriented Programming
- Consider two classes
- class Parent
- protected hasTallGene true
- protected int height 0
- public void grow( )
- height
- if (hasTallGene)
- height
-
-
61
62Object Oriented Programming
- Consider two classes
- class Child extends Parent
- public void playCounterstrike()
- // play!
-
-
- And the declarations
- Parent p new Parent( )
- Child c new Child( )
- Parent p2 new Child( )
- Child c2 (Child) p
62
63Object Oriented Programming
- What would happen for the following statements?
- i.e. Is it normal behavior, runtime error, or
compile time error? - p.grow( )
- c.grow( )
- p2.grow( )
- c2.grow( )
- p.playCounterstrike( )
- c.playCounterstrike( )
- p2.playCounterstrike( )
- c2.playCounterstrike( )
63
64Object Oriented Programming
- Why is OOP so cool?
- Reusable code
- How real world works (at least a good model of
it) - Public
- Private
- Static
- Inheritance
- Interfaces
64
65Object Oriented Programming
- Interfaces
- Can have field declarations and initializations
- But not method bodies
- Implements keyword used in implementing classes
- Pretty obvious if you say it this way!
- Like a Java class, filename must be same as
interface. Names usually end with -able - File Sortable.java
- public interface Sortable
- public void sort( )
- private Object maxValue null
65
66CS 9G Java Final Review
- Programming Assignments
- Applet Introduction Adding Machine
- Objects and Classes Cat and Mouse
- List Structures Butterfly
- Exception Handling Inventory
- Threads Bear
- Additional Topics
- Basic Java
- Object-oriented programming
- Data Structures
- Exceptions and Applications
66
67Data Structures
- Data structures are good when they are general
- Though there is more code involved
- Consider a backpack vs. a laptop sleeve. Backpack
is more versatile, can turn it into a laptop bag
by throwing a sweater in it laptop sleeve can
only hold a laptop
67
68Data Structures
- What is this extra work referring to?
- Remember what you put in the data structure
- What goes in is that which comes out
- Casting!
- Data structures usually store Object (general),
but if you want to perform specific operations on
those objects, they must be of the proper type - Asking an Object that you expect to be a
Butterfly for it's position will cause a
compile-time error, because Object does not store
a position
68
69Data Structures
- Operations you should be able to do
- Traverse it
- Search for something
- Convert it to another data structure (LinkedList
to array, array to Vector, Vector to LinkedList,
etc) - Sort it (if you're up to the challenge)
69
70Data Structures
- Arrays
- All members are of the same type
- Fixed size
- Easy to use if you don't need to grow the
collection - Examples in Inventory, Butterfly
- int blah new int 6
- Each value is initialized to 0
70
71Data Structures
- Vectors
- Each member can be a different type (though not
very useful) - Instead, a Vector is a general purpose data
structure - Growable
- Remember to cast when retrieving
- How to traverse a Vector, convert it to other
types
71
72Data Structures
- LinkedList
- Train analogy
- Be able to draw a box and pointer diagram
- Rearrange pointers
- Deleting nodes
72
73CS 9G Java Final Review
- Programming Assignments
- Applet Introduction Adding Machine
- Objects and Classes Cat and Mouse
- List Structures Butterfly
- Exception Handling Inventory
- Threads Bear
- Additional Topics
- Basic Java
- Object-oriented programming
- Data Structures
- Exceptions and Applications
73
74Exceptions
- See Inventory
- Common exceptions
- FileNotFoundException
- IOException
- ArrayIndexOutOfBoundsException
- Know these!
74
75Applications
- See Inventory
- Has main method
- public static void main (String args)
- Invoked by Java when running from the command
line - java InventoryTest inventory.data
- inventory.data is in the 0th position of args
- Review error handling in Inventory program
- Checking for files
75
76CS 9G Java Final Review
- You've made it through!
- The final won't be that hard if you could follow
most of the review, so relax ) - Can email Carol at selfpace_at_cs.berkeley.edu if
you really want to know your grade in a couple of
days (will only tell you whether you passed the
class). Otherwise, wait for it to be posted on
BearFacts.
76
77CS 9G Java Final Review
- Good skill on the final!
- Don't forget to enjoy your break!
77