CS 9G – Java – Final Review - PowerPoint PPT Presentation

Cs 9g java final review
Download
1 / 77

CS 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_final_review.ppt PDF

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

Download Presentation

CS 9G – Java – Final Review

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Cs 9g java final review

CS 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_final_review.ppt

    • PDF

      http://www.ocf.berkeley.edu/~jontsai/files/cs9g_final_review.pdf

1


Cs 9g java final review1

CS 9G – Java – Final Review

  • CS 9G Final (You should have already signed up)

    • Tuesday, December 14

    • 8-11am, 12:30-3:30 or 5-8pm. All in the Bechtel Auditorium

  • For updated info check: http://www-inst.eecs.berkeley.edu/~selfpace

  • Worth 40% of your grade

  • Need about 70% in class to pass (I'm not sure about this exactly)

2


Cs 9g java final review2

CS 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


Cs 9g java final review3

CS 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


Cs 9g java final review4

CS 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


Adding machine

Adding Machine

  • Applet

    • import java.applet.Applet

    • public void init ( )

    • public void paint (Graphics)

  • Widgets

    • TextField

    • Button

  • Other

    • public void actionPerformed(Event)

6


Adding machine1

Adding Machine

  • Applet

    • import java.applet.Applet

    • public void init ( )

    • public void paint (Graphics)

  • Widgets

    • TextField

    • Button

  • Other

    • public void actionPerformed(Event)

7


Adding machine2

Adding Machine

  • public void init( )

    • Called whenever starting an applet

    • HTML code:

      <applet code=“AddingMachine.class” width=300 height=200></applet>

    • Set up objects

    • If have additional parameters to retrieve from HTML code to Applet

      Inside <applet ...> and </applet>, for each parameter put

      <param name="your_param_name" value="your_value">

8


Adding machine3

Adding Machine

  • Applet

    • import java.applet.Applet

    • public void init ( )

    • public void paint (Graphics)

  • Widgets

    • TextField

    • Button

  • Other

    • public void actionPerformed(Event)

9


Adding machine4

Adding 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


Adding machine5

Adding Machine

  • Applet

    • import java.applet.Applet

    • public void init ( )

    • public void paint (Graphics)

  • Widgets

    • TextField

    • Button

  • Other

    • public void actionPerformed(Event)

11


Adding machine6

Adding 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


Adding machine7

Adding Machine

  • Applet

    • import java.applet.Applet

    • public void init ( )

    • public void paint (Graphics)

  • Widgets

    • TextField

    • Button

  • Other

    • public void actionPerformed(Event)

13


Adding machine8

Adding 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


Cs 9g java final review5

CS 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


Cat and mouse

Cat and Mouse

16


Cat and mouse1

Cat and Mouse

  • Four Classes

    • CatMouseChase.java

    • Cat.java

    • Mouse.java

    • Position.java

  • CatMouseChase was the Applet that controlled display and mouse interaction, etc

17


Cat and mouse2

Cat 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


Cat and mouse3

Cat 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


Cs 9g java final review6

CS 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


Butterfly

Butterfly

  • 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


Butterfly1

Butterfly

  • 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


Butterfly2

Butterfly

  • 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


Cs 9g java final review7

CS 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


Inventory

Inventory

  • 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


Inventory1

Inventory

  • 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


Inventory2

Inventory

  • When something bad happens, we'd like to throw an exception

    if (something_bad_happens) {

    thrownew 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


Inventory3

Inventory

  • 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


Inventory4

Inventory

  • 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


Cs 9g java final review8

CS 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


Cs 9g java final review

Bear

31


Cs 9g java final review

Bear

  • 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


Cs 9g java final review

Bear

  • 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


Cs 9g java final review

Bear

  • 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


Cs 9g java final review

Bear

  • 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


Cs 9g java final review

Bear

  • How do I make a thread, say BearDisplayer?

    class BearDisplayer extends Thread {

    public voidrun( ) {

    // 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


Cs 9g java final review9

CS 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


Basics

Basics

  • 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


Basics1

Basics

  • 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


Basics2

Basics

  • Integer division

    int i = 5;

    i = 5 / 2;

    System.out.println(i);

  • What gets printed out?

40


Basics3

Basics

  • 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


Basics4

Basics

  • 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


Basics5

Basics

  • Decisions: if and switch

  • if (just like C)

    if (something) {

    } else {

    }

  • Can be nested

    if (something) {

    } else {

    if (something_else) {

    } else {

    }

    }

43


Basics6

Basics

  • This block of statements

    if (something) {

    } else {

    if (something_else) {

    } else {

    }

    }

  • Is equivalent to

    if (something) {

    } else if (something_else) {

    } else {

    }

44


Basics7

Basics

  • 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


Basics8

Basics

  • 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


Basics9

Basics

  • For loop

    for (int i=0; i < array.length; ++i) {

    // Do something

    }

  • While loop

    while (somethingIsTrue) {

    // Do something

    }

47


Cs 9g java final review10

CS 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


Object oriented programming

Object 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


Object oriented programming1

Object 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


Object oriented programming2

Object 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


Object oriented programming3

Object 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


Object oriented programming4

Object 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


Object oriented programming5

Object 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


Object oriented programming6

Object 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


Object oriented programming7

Object 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


Object oriented programming8

Object 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


Object oriented programming9

Object 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


Object oriented programming10

Object 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


Object oriented programming11

Object 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


Object oriented programming12

Object Oriented Programming

  • Consider two classes:

    class Parent {

    protected hasTallGene = true;

    protected int height = 0;

    public void grow( ) {

    height++;

    if (hasTallGene) {

    height++;

    }

    }

    }

61


Object oriented programming13

Object 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


Object oriented programming14

Object 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


Object oriented programming15

Object 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


Object oriented programming16

Object 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


Cs 9g java final review11

CS 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


Data structures

Data 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


Data structures1

Data 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


Data structures2

Data 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


Data structures3

Data 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


Data structures4

Data 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


Data structures5

Data Structures

  • LinkedList

    • Train analogy

    • Be able to draw a box and pointer diagram

    • Rearrange pointers

    • Deleting nodes

72


Cs 9g java final review12

CS 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


Exceptions

Exceptions

  • See Inventory

  • Common exceptions

    • FileNotFoundException

    • IOException

    • ArrayIndexOutOfBoundsException

  • Know these!

74


Applications

Applications

  • 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


Cs 9g java final review13

CS 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@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


Cs 9g java final review14

CS 9G – Java – Final Review

  • Good skill on the final!

  • Don't forget to enjoy your break!

77


  • Login