CIS 265 Notes Part 1
CIS 265 Notes Part 1
Review of OOP
Challenging
How to do well
Attend class regularly with the notes and have read the material
assigned for the week before the week starts
You have already paid $$$ for my office hours - USE THEM
Java
Java supports safe computing. The JVM first checks Java code to be
sure that it can not do anything malicious before running it. This
3
is especially true of Java applets (small Java programs downloaded
off of web pages). This increases the safety of running Java
programs, but at the cost of increased start up times. The later
issue is one reason why there are very few web sites that have client
side executable Java content any more, despite the safety guarantee
OOP
Dynamic Binding is a nuts and bolts concept that goes hand and hand
with inheritance. While, not one of the prime concepts of OOP, it is
required to handle inheritance correctly. Essentially, if code
expects one object, it will also work with any inherited object (More
on this much later)
Java has a variety OOP Structures are used to embody the key OOP
concepts we previously mentioned. The basic Java structures are
JVM is not perfect, you can create code that will cause
Java to fail to garbage collect correctly (thankfully this
is rare!) This causes a memory leak where each run of the
7
program (or over time) consumes more memory than it frees
up
The constructor is the method that runs once, when each object is
first instantiated. Typically this is used for initializing the
default values of the object. The constructor method must be named
the same as the class but you can have a different versions based on
parameters. If you do not provide constructor(s), then the default
version is automatically provided, although it does nothing special
Examples)
Examples)
Examples)
A House
house has a refridgerator
house has a oven
house has a bedroom
Example of Composition)
fraction()
{
iNum = 1;
iDen = 1;
}
answer.set(iNewNum, iNewDen);
return answer;
}
System.out.print("answer = ");
answer.output();
Example of Inheritance)
fraction()
{
iNum = 1;
iDen = 1;
}
answer.set(iNewNum, iNewDen);
}
answer.set(iNewNum, iNewDen);
}
}
12
// Class test in its own file
// uses fraction class
public class test
{
public static void main( String args[] )
{
fraction2 frac1 = new fraction2();
fraction2 frac2 = new fraction2();
fraction2 answer = new fraction2();
frac1.set(4,5);
frac2.set(2,3);
frac1.add(frac2, answer);
frac1.mult(frac2, answer);
· If you trace back through the code the most recent method or
variable declaration and definition in a class is the correct one to
use. That is a local scope always takes precedence over a global
scope.
· To make call by value work like call by reference you will need to
pass the values using a specialized object designed for this and then
changing them will work like call by reference because it is
Static modifier means that there will be only one method ever
created for any number of objects. A static method may access static
field variables or call other static methods from the same class.
You may instantiate local objects and access their properties
normally
Method Arguments and Parameters in Java are predefined to use call by
value for all primitives, and call by reference for all objects, no
exceptions
Examples of Scope)
// Class test
// shows off scope
meth1(iA, iB);
meth2(iX, iY);
} // end meth2
// Class test
// shows off scope & return
iB = meth2(iX, iY);
return( 23 );
} // end meth2
GUI Events
Events are actions that can cause programmer changeable code to run.
Examples of events include a printer reporting out of paper, a user
clicking a mouse, each character entered in a text box, etc. If the
programmer does not over ride these actions, then they do whatever
they would normally do (usually very little). However, it is
possible to use inheritance to add code to events so that they can do
more (or less) then what is normally done
All Events are originally triggered by the OS. This in turn passes
the event objects to the Java Virtual Machine (JVM, more later). The
JVM periodically checks to see what events it has. If someone’s Java
program has some special event code that matches that event, it will
run that code
Event Source which object triggered (is affected by) the event
Event Listener is the code which waits to receive the event object.
It must both be registered with the event source as well as have code
that will handle the event in question. This is the portion we
write to handle events
An Event is triggered
Periodically, the JVM looks for any events that it should handle
The event listeners we can use are provided as interfaces that you
can implement in your code. Generally, this is done by the use of
inner classes. The event interface system is as follows
EventListener
ActionListener
AdjustmentListener
ComponentListener
ContainerListener
FocusListener
ItemListener
KeyListener
MouseListener
MouseMotionListener
TextListner
19
WindowListener
Inner Classes and Anonymous Inner Classes are two ways we can use to
create our event classes. Both involve creating a class inside a
class (our GUI class)
Code Example)
// set up GUI
public TextFieldTest()
{
super( "Testing JTextField and JPasswordField" );
Code Example)
// set up GUI
public ButtonTest()
{
super( "Testing Buttons" );
// create buttons
plainButton = new JButton( "Plain Button" );
container.add( plainButton );
Combining Both
// Creating test5
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// set up GUI
public test5()
{
super( "Testing Buttons" );
// create buttons
plainButton = new JButton( "Plain Button" );
container.add( plainButton );
You can get an older version of Java off of the CD that comes with
the course book. However, a newer free version is located at
http://java.sun.com/j2se/1.4.2/download.html. Note that this is a
big download. Do it over night if you are a modem user (or go to a
friend’s house with broadband and burn a CD from him/her)
25
I do not recommend the IDE that comes on the CD. It is very slow,
difficult to use and quite buggy. To get a decent free IDE that
works on all Windows versions that I am aware of, try going to the
site http://www.jcreator.com/ and downloading the current free
version of JCreator LE. It is only a 1.8 meg download. A “Pro”
version featuring inteli-sense is about $30 and well worth it.
If you wish to use Java from the command line you will need to set
the Path Environment Variable. Under XP / 2000 this can be set in
control panel -> system -> advanced -> environment variables ->
system variables -> path. Add the following to the path to make it
look like the end of this line ( That assumes that is the version and
location where Java is installed for you – should be correct if you
downloaded from Sun’s site above and changed nothing during
installation )
Arrays
Notes on Arrays
Arrays have built in methods such as length() that help keep track
of things for you that you might otherwise have had to track
yourself. Of course, such method calls have the same overhead as
standard method calls
Code Example)
// SumArray.java
// Total the values of the elements of an array.
public class SumArray
{
System.out.println();
System.exit( 0 );
} // end main
Code Example)
// Pass Array
// Passing arrays and individual array elements to methods.
public class SumArray
{
System.out.println(“”);
System.exit( 0 );
} // end main
// multiply argument by 2
public static void modifyElement( int element )
{
element *= 2;
}
or
int array[3][2];
Example)
// Pass Array2d
// Passing arrays and individual array elements to methods.
public class test3
{
System.out.println("");
System.exit( 0 );
} // end main
// Pass Array
// Passing arrays and individual array elements to methods.
public class test3
{
System.out.println("");
System.exit( 0 );
} // end main
Big O Notation
33
Only the most expensive nested loop counts toward the maximum total
evaluation for the algorithm. So a program with a nested loop of N,
N and log N, followed by another nested loop of N and N evaluates to
just N2 log N
O(1)
O(log N)
O(N)
O(N log N)
O(N2)
O(N2 log N)
O(N3)
. . .
O(2N) // Here we leave the realm of polynomials and enter
// exponentials
Searching
Snippet Example)
iKey = 100;
Bfound = false;
for ( lcv = 0; lcv < array.length; lcv++)
{
if ( array[lcv] == iKey )
{
bFound = true;
break;
}
}
Snippet Example)
// bin search
// tbl The table of elements
// n The element to be searched for
OOP Design
OOP Design is almost a field unto itself. The flexibility and power
of OOP come at a price of increased code complexity as well as
increased design complexity. One common approach with data
structures is to have the data itself as one (or more) classes and
anther class to serve as the data structure itself. The main
application (consisting of however many classes) accesses the data
structure, but rarely the data objects themselves to do more than
create or read them. Some things to note
Not Truly Generic* funnily enough, Java lacks both templates and
overloaded operators which, if present, would allow us to create
universal algorithms and data structures. We can work around some of
these constraints with polymorphism, base object types and
reflection, but it is fairly ugly
Code Example)
// highArray.java
// demonstrates array class with high-level interface
// to run this program: C>java HighArrayApp
////////////////////////////////////////////////////////////////
class HighArray
{
private long[] a; // ref to array a
private int nElems; // number of data items
// Main app
////////////////////////////////////////////////////////////////
class HighArrayApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
HighArray arr; // reference to array
arr = new HighArray(maxSize); // create the array
Code Example)
// classDataArray.java
// data items as class objects
// to run this program: C>java ClassDataApp
////////////////////////////////////////////////////////////////
class Person
{
private String lastName;
private String firstName;
private int age;
// Data structure
/////////////////////////////////////////////////////////
class ClassDataArray
{
private Person[] a; // reference to array
private int nElems; // number of data items
41
public ClassDataArray(int max) // constructor
{
a = new Person[max]; // create the array
nElems = 0; // no items yet
}
// main code
////////////////////////////////////////////////////
class ClassDataApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
ClassDataArray arr; // reference to array
arr = new ClassDataArray(maxSize); // create the array
// insert 10 items
Sorting
In Order refers to a sort that keeps equal valued keys in the same
order they initially appeared in
Best Case, Average Case and Worst Case may or may not be different
for a particular sort algorithm. For example, a quick sort is O(N
log N) on average, but if data is almost sorted already, it is O(N2).
The basic sorts in this chapter do not have different cases
Simple Sorts All of the simple sorts presented In this chapter are
O(N2), in place and in order. Note that just because they are simple
and slow, does not mean that they do not have uses. They are quick
to code and have low constants so are actually quicker than some of
their fancier brethren for small sizes of N
Bubble Sort works by an outer loop making N passes over N data. Each
inner loop pass then looks at successive pairs of elements in order.
If the inner loop finds that one element is smaller than its
predecessor, it swaps them
Example Code)
////////////////////////////////////////////////////////////////
class BubbleSortApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
ArrayBub arr; // reference to array
arr = new ArrayBub(maxSize); // create the array
Example Code)
// selectSort.java
// demonstrates selection sort
// to run this program: C>java SelectSortApp
////////////////////////////////////////////////////////////////
class ArraySel
{
private long[] a; // ref to array a
private int nElems; // number of data items
////////////////////////////////////////////////////////////////
class SelectSortApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
ArraySel arr; // reference to array
arr = new ArraySel(maxSize); // create the array
Example Code)
// insertSort.java
// demonstrates insertion sort
// to run this program: C>java InsertSortApp
//--------------------------------------------------------------
class ArrayIns
{
private long[] a; // ref to array a
private int nElems; // number of data items
////////////////////////////////////////////////////////////////
class InsertSortApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
ArrayIns arr; // reference to array
arr = new ArrayIns(maxSize); // create the array
Objects
Objects cannot be compared with =, <, >, etc, because the value
stored in the reference variable is
Example Code)
52
// objectSort.java
// demonstrates sorting objects (uses insertion sort)
// to run this program: C>java ObjectSortApp
////////////////////////////////////////////////////////////////
class Person
{
private String lastName;
private String firstName;
private int age;
////////////////////////////////////////////////////////////////
class ObjectSortApp
{
public static void main(String[] args)
{
int maxSize = 100; // array size
ArrayInOb arr; // reference to array
arr = new ArrayInOb(maxSize); // create the array
System.out.println("Before sorting:");
System.out.println("After sorting:");
arr.display(); // display them again
} // end main()
} // end class ObjectSortApp
Stack
A Stack is much like a can of tennis balls, the first ball out of the
can was the last one in the can. This is referred to as a LIFO (list
in, first out) structure in computer science. Stacks can be created
with both lists and arrays (which we will focus on here). A stack
has essentially two basic operations with several optional helper
methods
Peek which looks at the item from the top of the stack (no removal)
Code Example)
// stack.java
// demonstrates stacks
// to run this program: C>java StackApp
////////////////////////////////////////////////////////////////
class StackX
{
private int maxSize; // size of stack array
private long[] stackArray;
private int top; // top of stack
////////////////////////////////////////////////////////////////
class StackApp
{
public static void main(String[] args)
{
StackX theStack = new StackX(10); // make new stack
theStack.push(20); // push items onto stack
theStack.push(40);
theStack.push(60);
theStack.push(80);
Code Example)
////////////////////////////////////////////////////////////////
class Reverser
{
private String input; // input string
private String output; // output string
////////////////////////////////////////////////////////////////
class ReverseApp
{
public static void main(String[] args) throws IOException
{
String input, output;
while(true)
{
58
System.out.print("Enter a string: ");
System.out.flush();
input = getString(); // read a string from kbd
if( input.equals("") ) // quit if [Enter]
{
break;
}
// make a Reverser
Reverser theReverser = new Reverser(input);
output = theReverser.doRev(); // use it
System.out.println("Reversed: " + output);
} // end while
} // end main()
Queues
A Queue is much like a line you would wait in, the first person in
line is the first to get out of the line. In computer science this
type of structure is referred to as FIFO (first in, first out).
Queues can be created with both lists and arrays (which we will focus
on here). There are several flavors of queues, but all have
essentially two basic operations with several optional helper methods
DeQueue which removes and item from the front of the queue
59
Peek which looks at the item from the front of the queue (no
removal)
A Circular Queue is a queue, but the enqueue and the dequeue can wrap
around ends of the array by using mod
A Deque stands for doubly ended queue which allows enquing and
dequing from either end of the queue. Best done with a circular
queue
A Priority Queue works like any other queue, except that items are
queued up according to some other priority rather than arrival time.
In this case we must slide values down when we prioritize them, so a
circular implementation will not help here
Code Examples)
// Queue.java
// demonstrates queue
// to run this program: C>java QueueApp
60
////////////////////////////////////////////////////////////////
class Queue
{
private int maxSize;
private long[] queArray;
private int front;
private int rear;
private int nItems;
////////////////////////////////////////////////////////////////
class QueueApp
{
public static void main(String[] args)
{
Queue theQueue = new Queue(5); // queue holds 5 items
Hybrid Array
A Hybrid (Dynamic) Array is one that can be resized on the fly. This
is important because arrays normally are fixed in size which
frequently leads to either an over flow because they are too small,
or over utilization of memory. There are two things that we need to
do to create generic dynamic arrays
Allow the array to change size during the data structures use.
Typically we pick some break points to do this. For example, if
array falls beneath 25% utilization, shrink its size by half.
Conversely if the array is full, double its size. Both c neb
accomplished by creating a new array (sized appropriately) and
copying the old array into it. Then set the old array reference to
equal the new array and it will be transparent
Code Example)
TBD In class