Option D: Object-Oriented Programming Revision Guide
Option D: Object-Oriented Programming Revision Guide
Option D: Object-Oriented Programming Revision Guide
A class is a template for creating these objects. The class identifies what data needs to be
stored (fields) for objects of this type and what methods are available to allow access to this data.
For example: The following boxes show example classes. The top half of the box shows the
fields and the bottom half the methods
The constructor method of the class has the same name as the class.
In the execution of a program the word object has a slightly different meaning. Here, an object is
created by a constructor of the class, the resulting object is called an instance of the class. So in
this example the class is a template for a lottery draw but you would have a new lottery object
each Saturday for each new draw, each draw object having its own set of winning numbers for
example. Similarly, you can generate lots of lottery ticket objects. They all follow the same
structure but would have different numbers assigned to each object.
Molly and Alice in your IA, you had a class student. You then created a number of instances of
this class (objects) called Angus, Theo, Ruby etc. They all had addresses, parents, houses,
numEvents etc but they were all different. An instance of a class is when the program has
allocated memory to hold the object i.e. the object exists at runtime (Instantiation).
D1.3 & D1.4 UML Diagrams and their interpretation
This is simply asking you to be able to draw object and class diagrams like in the previous example
and in your IA. It is the way in which we visualise our computational thinking and program design.
Object Diagram
In this example the Customer Object ‘Customer1’ is associated with 3 order objects Order1, Order2
and Order 3.
Class Diagram
In this class diagram you have an Order class with fields: dateReceived of type Date; isPrepaid of
type Boolean; number of type String and price of type Money. It has methods called: dispatch() and
close(). You don’t know how those methods work you just know that you have access to them. The
name of the methods should indicate what the method does.
You also have a class called Customer. All customers have a name field and an address field and a
method called creditRating(). The classes Corporate Customer and Personal Customer are types of
customer so the diagram shows (by the arrows) that they INHERIT all the fields and methods of the
customer class. On top of this they have their own specific fields and methods which they do not
share.
D1.5 Describe the process of decomposition into several
related objects
This we did in year 12 when we looked at the digital clock in java. The clock is made of 2 two digit
number displays so we created a class numberDisplay and a class clockDisplay which consisted of 2
numberDisplay objects. (ABSTRACTION)
As another example, you may have a real-world object of a calendar. The calendar is made up of
days which can be grouped into weeks which can be grouped into months etc. You have
decomposed the calendar into days, weeks and months; its component parts.
1. Dependency (“uses”)
2. Aggregation (“has a”)
3. Inheritance (“is a”)
Here, the courseSchedule class depends on the course class because the add() and remove()
methods both use the Course class.
Aggregation
Here, the Car class includes fields of type Engine and Transmission classes. The Engine class and
Transmission class objects can exist in isolation of the car class.
Inheritance
Two classes that use each other are called "coupled". The coupling between classes can be loose or
tight, or somewhere in between. The tightness of a coupling is not binary. It is not either "loose" or
"tight". The degrees of tightness are continuous, not discrete. You can also characterize
dependencies as "strong" or "weak". A tight coupling leads to strong dependencies, and a loose
coupling leads to weak dependencies, or even no dependencies in some situations.
Dependencies, or couplings, are directional. That A depends on B doesn't mean that B also depends
on A.
Imagine you have a class CalendarReader that is able to read a calendar event list from an XML file.
The implementation of CalendarReader is sketched below:
The method readCalendarEvents takes a File object as parameter. Thus this method depends on the
File class. This dependency on the File class means that the CalendarReader is capable only of
reading calendar events from local files in the file system. It cannot read calendar event files from a
network connection, a database or from a resource on the classpath. You can say that the
CalendarReader is tightly coupled to the File class and thereby the local file system.
A less tightly coupled implementation would be to exchange the File parameter with an InputStream
parameter, as sketched below:
As you may know, an InputStream can be obtained from either a File object, a network Socket, a
URLConnection class, a Class object (Class.getResourceAsStream(String name)), a column in a
database via JDBC etc. Now the CalendarReader is not coupled to the local file system anymore. It
can read calendar event files from many different sources.
With the InputStream version of the readCalendarEvents() method the CalendarReader has become
more reusable. The tight coupling to the local file system has been removed. Instead it has been
replaced with a dependency on the InputStream class. The InputStream dependency is more flexible
than the File class dependency, but that doesn't mean that the CalendarReader is 100% reusable. It
still cannot easily read data from a NIO Channel, for instance.
(ref: http://tutorials.jenkov.com/ood/understanding-dependencies.html#whatis)
There are other overheads with dependencies in terms of maintaining the code, you need to be very
careful that you have considered the impact of code changes on all classes involved in the
dependency relationship to retain the integrity of your program. This can increase the length of time
the work takes therefore incurring more costs in the production of the code. There is greater room
for error and human oversight etc.
String
Used to represent a sequence of characters like a name. (In Java, string is a class not a data type as it
has a set of associated methods.) Each character is stored in a byte of memory
Boolean
Used to represent data that can only take two values e.g. true/false; on/off; male/female. It occupies
1 bit of data in memory
We need different data types because we have different sorts of data. All data must be converted
into binary in order for it to be stored and processed by the computer. Each data types ‘tells’ the
computer how to deal with the data it is given and how much memory space the data will use. By
choosing the correct data type we can control how much memory our program will use.
int x = 3;
If the main program wanted the new value of p returned the code would look like this:
int x = 3;
int y = 0;
If you think of an object that is an instance of a class called File, then the object is likely to provide
methods to open, close and read a file. Other objects using these methods do not know how the
method is implemented(how it works internally). So in the case of the File example the calling object
does not know how the file object will open the file, it just knows that it will. This is akin to a
managing director of a business asking a software developer to add some new services to the
company website. The director isn't interested in how the developer does it they just want the
services to be added.
Advantages of Encapsulation
Let's imagine we have two objects, the first we will call "evil object" and the second
object we will call "account object". The account object has a data attribute called
"balance". If this attribute is public, allowing other objects to manipulate its value then
the evil object can change it to whatever it wants. This means you could go from having
£100 in your account to having £0 in your account. To address this situation we can
make the balance attribute private and add a method called "AddFunds". This means
that now the account balance can only go up, or does it? Have a look at the following
diagram.
The evil object is invoking the AddFunds method but is passing a value of -£50. This
means that instead of adding funds the balance would actually go down. We can address
this issue by building checks into the AddFunds method, for example we could use the
following logic:
Method: ADDFUNDS, Parameter: AMOUNT
Now we have some control on how the data can be accessed and modified. This type of
check would not be possible with public data and direct modification access.
The shielding of the data means that should the format of the private data need to
change for some reason the objects calling the methods on the object whose data has
changed will not need to change the way they call the method. For example, if we
imagine that we needed to change a data attribute from a type float to a type double.
(Both represent real numbers but the double type can typically store larger values.) If a
calling object is updating the value directly then by changing the data type you will also
need to change the code in the calling object. If you are dealing with large systems with
hundreds of classes this type of situation can quickly get out of hand with several layers
of "knock-on" changes required. Therefore we would say that encapsulation promotes
maintenance because code changes can be made independently without affecting other
classes.
(ref:
http://www.cems.uwe.ac.uk/~jsa/UMLJavaShortCourse09/CGOutput/Unit3/unit3(0809)/
page_12.htm)
D2.2 & D2.5 Define the term inheritance, explain the
advantages of inheritance
Inheritance
A parent object holds common fields and methods for a group of related child objects. For example,
a Person Class will hold common fields and methods for a Student class and a Teacher class.
For example:
Advantages of Inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in an application
by sharing common code amongst several subclasses. Where equivalent code exists in two related
classes, the hierarchy can usually be refactored to move the common code up to a mutual
superclass. This also tends to result in a better organization of code and smaller, simpler compilation
units.
Reusability - facility to use public methods of superclass class without rewriting the same code
Overriding – Methods can be implemented in the subclass that override methods of the same name
in the superclass to make the methods more suitable for the subclass.
Data hiding - Superclass can decide to keep some data private so that it cannot be altered by the
subclass.
1.One of the main disadvantages of inheritance in Java (the same in other object-oriented
languages) is the increased time/effort it takes the program to jump through all the levels of
overloaded classes. If a given class has ten levels of abstraction above it, then it will essentially take
ten jumps to run through a function defined in each of those classes
2.Main disadvantage of using inheritance is that the two classes (super and subclass) get tightly
coupled. This means one cannot be used independently of the other.
3. Also with time, during maintenance adding new features both base as well as derived classes are
required to be changed. If a method signature is changed then we will be affected in both cases.
4. If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of
using that method. Here things can get a bit complicated in case of inheritance because our
programs will still compile, but the methods of the subclass will no longer be overriding superclass
methods. These methods will become independent methods in their own right.
(ref: http://erpbasic.blogspot.co.uk/2012/01/inheritance-advantages-and.html)
D2.3 & D2.6 Define the term polymorphism, explain the
advantages of polymorphism
Polymorphism
Methods have the same name but different parameter lists and processes. Polymorphism can be
demonstrated with a minor modification to the Bicycle class. For example,
a printDescription method could be added to the class that displays all the data currently
stored in an instance(object of that class).
public MountainBike(
int startCadence,
int startSpeed,
int startGear,
String suspensionType){
super(startCadence,
startSpeed,
startGear);
this.setSuspension(suspensionType);
}
Next, create the RoadBike class. Because road or racing bikes have skinny tires, add an attribute to
track the tire width. Here is the RoadBikeclass:
public class RoadBike extends Bicycle{
// In millimeters (mm)
private int tireWidth;
To summarize, there are three classes: Bicycle, MountainBike, and RoadBike. The two
subclasses override the printDescription method and print unique information.
Here is a test program that creates three Bicycle variables. Each variable is assigned to one of the
three bicycle classes. Each variable is then printed.
bike01.printDescription();
bike02.printDescription();
bike03.printDescription();
}
}
The following is the output from the test program:
Bike is in gear 1 with a cadence of 20 and travelling at a speed of 10.
Now, Java only lets you put one type of thing into a collection (you need to understand this data
structure). You don't want to have a porsche list, a corvette list, and a yugo list - you want a list of
cars - so that's what you do, create a superclass of car and subclasses for each car type (inheritance).
Then, since all of these ARE cars, you can put them all into the collection.
Then you want to start each and every car once a week (to keep it in good condition). You want to
iterate through your collection and call each car's start() method. You can do this:
There are several beautiful things about this. First, you don't need to code it like this:
Look at these two code examples. Now imagine that after a few years, we decide to buy a BMW. In
the first example, you don't need to touch the code, and it will handle a BMW just fine.
This means that the first code example can hand object types THAT DIDN'T EXIST when you originally
wrote it. The less you have to touch code, the less likely you are to introduce a bug. The second code
example would need to be updated each and every time I want to buy a new type of car. Not good!
The Polymorphism here is in the implementation of the start() method which would be different for
each type of car. The calling program however, sees it as the same (implementation is hidden)
(ref: http://www.coderanch.com/t/548649/java-programmer-SCJP/certification/point-advantage-
polymorphism)
D2.7 The Advantages of Libraries of Objects
Libraries are made available for code that is likely to be re-used. Examples of this are standard
search and sorting algorithms or file handling methods. By providing the code in a library the
programmer does not have to keep re-inventing the wheel. The code that is contained in the library
has been tested and is reliable. In java libraries are used in the code by ‘importing’ them at the top
of a class e.g.
import java.lang.Math.*;
Size: Object Oriented programs are much larger than other programs. In the early days of
computing, space on hard drives, floppy drives and in memory was at a premium. Today we do not
have these restrictions.
Effort: Object Oriented programs require a lot of work to create. Specifically, a great deal of planning
goes into an object oriented program well before a single piece of code is ever written. Initially, this
early effort was felt by many to be a waste of time. In addition, because the programs were larger
(see above) coders spent more time actually writing the program.
Speed: Object Oriented programs are slower than other programs, partially because of their size.
Other aspects of Object Oriented Programs also demand more system resources, thus slowing the
program down.
Not suitable for all types of problems: There are problems that lend themselves well to functional-
programming style, logic-programming style, or procedure-based programming style, and applying
object-oriented programming in those situations will not result in efficient programs.
In recent years, however, improvements in computer performance have made restrictions about
size and speed inconsequential. The question of human effort still exists, however; many novice
programmers do not like Object Oriented Programming because of the great deal of work required
to produce minimal results.
Code Reuse and Recycling: Objects created for Object Oriented Programs can easily be
reused in other programs.
Encapsulation (part 1): Once an Object is created, knowledge of its implementation is not
necessary for its use. In older programs, coders needed understand the details of a piece of
code before using it (in this or another program).
Encapsulation (part 2): Objects have the ability to hide certain parts of themselves from
programmers. This prevents programmers from tampering with values they shouldn't.
Additionally, the object controls how one interacts with it, preventing other kinds of errors.
For example, a programmer (or another program) cannot set the width of a window to -400.
Design Benefits: Large programs are very difficult to write. Object Oriented Programs force
designers to go through an extensive planning phase, which makes for better designs with
less flaws. In addition, once a program reaches a certain size, Object Oriented Programs are
actually easier to program than non-Object Oriented ones.
Software Maintenance: Programs are not disposable. Legacy code must be dealt with on a
daily basis, either to be improved upon (for a new version of an exist piece of software) or
made to work with newer computers and software. An Object Oriented Program is much
easier to modify and maintain than a non-Object Oriented Program. So although a lot of
work is spent before the program is written, less work is needed to maintain it over time.
This way of splitting the work up obviously needs careful planning and good communication
between team members. Its success also relies on everyone pulling their weight as at some point the
system will have to be pieced together for testing and you might start to get bottlenecks if team
members have to wait for others to complete before they can proceed.
Benefits
Attack bigger problems in a short period of time
Utilize the collective experience of everyone (people can work to their strengths)
Risks
Communication and coordination issues
Groupthink: diffusion of responsibility; going along
Working by inertia; not planning ahead
Conflict or mistrust between team members
Instance variable: The fields in a class. So when an object is created of that class type, it has its own
version of the fields (instance variables)
Parameter variable: Information sent into a method from the calling program e.g
public int add(int x, int y) The calling problem might look something like this:
{
Add(firstNum,secondNum)
Return x+y
} Here firstNum & secondNum are all parameter variables
Local variable: A local variable exists only as long as the code to which it belongs exist. So if it is
declared in a method, when the method is no longer in use during the run of a program, the variable
no longer exists(memory is not used to store them anymore, its overwritten). The arguments are
used as local variables.
Method: A program routine contained within an object designed to perform a particular task on the
fields within the object.
Accessor: A method that allows access to the fields within an object e.g. getName()
Mutator: A method that allows the values of the fields in an object to be changed e.g. setName()
Constructor: The method that correctly initialises and sets up an object when it is created. This
method has the same name as the class it belongs to and no return datatype e.g. public person()
Private: Methods, Fields and Constructors that are declared private can only be accessed within the
declared class itself. Private access modifier is the most restrictive access level. Classes cannot be
private. Fields that are declared private can be accessed outside the class if public accessor methods
are present in the class. Using the private modifier is the main way that an object encapsulates itself
and hides its data from the outside world.
Protected: Variables, methods and constructors which are declared protected in a superclass can be accessed
only by the subclasses in other package or any class within the package of the protected members'
class. The protected access modifier cannot be applied to classes. Methods and fields can be
declared protected.
Public:A class, method, constructor etc declared public can be accessed from any other class.
Therefore fields, methods, blocks declared inside a public class can be accessed from any class
belonging to the Java Universe. Because of class inheritance, all public methods and fields of a class
are inherited by its subclasses.
Extends: This keyword is used by a subclass to say that it inherits the fields and methods from a
superclass (see inheritance earlier)
Static: In Java, a static member is a member of a class that isn’t associated with an instance of a class.
Instead, the member belongs to the class itself. As a result, you can access the static member
without first creating a class instance.
The two types of static members are static fields and static methods:
Static field: A field that’s declared with the static keyword, like this:
The value of a static field is the same across all instances of the class. In other words, if a class
has a static field named CompanyName , all objects created from the class will have the same
value for CompanyName .
Static fields are created and initialized when the class is first loaded. That happens when a static
member of the class is referred to or when an instance of the class is created, whichever comes
first.
Static method: A method declared with the static keyword. Like static fields, static methods are
associated with the class itself, not with any particular object created from the class. As a result,
you don’t have to create an object from a class before you can use static methods defined by the
class.
The best-known static method is main , which is called by the Java runtime to start an
application. The main method must be static , which means that applications run in a static
context by default.
One of the basic rules of working with static methods is that you can’t access a nonstatic
method or field from a static method because the static method doesn’t have an instance of
the class to use to reference instance methods or fields.
D3.4 Describe the uses of the primitive data types and the
reference class string
Byte:
Byte data type is an 8-bit signed two's complement integer.
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers, since a byte
is four times smaller than an int.
Int:
Int data type is a 32-bit signed two's complement integer.
Int is generally used as the default data type for integral values unless there is a concern
about memory.
Long:
Long data type is a 64-bit signed two's complement integer.
This data type is generally used as the default data type for decimal values, generally the
default choice.
Double data type should never be used for precise values such as currency.
Boolean:
boolean data type represents one bit of information.
This data type is used for simple flags that track true/false conditions.
Char:
char data type is a single 16-bit Unicode character.
The commonly-used method in the String class are summarized below. Refer to the JDK API
for java.lang.String a complete listing.
// Length
int length() // returns the length of the String
boolean isEmpty() // same as thisString.length == 0
// Comparison
boolean equals(String another) // CANNOT use '==' or '!=' to compare two Strings
in Java
boolean equalsIgnoreCase(String another)
int compareTo(String another) // return 0 if this string is the same as another;
// <0 if lexicographically less than another; or >0
int compareToIgnoreCase(String another)
boolean startsWith(String another)
boolean startsWith(String another, int fromIndex) // search begins at fromIndex
boolean endsWith(String another)
// Creating a new String or char[] from the original (Strings are immutable!)
String toLowerCase()
String toUpperCase()
String trim() // create a new String removing white spaces from front and
back
String replace(char oldChar, char newChar) // create a new String with oldChar
replaced by newChar
String concat(String another) // same as thisString + another
char[] toCharArray() // create a char[] from this string
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) // copy into
dst char[]
For example:
D3.7 Construct code examples related to selection
statements
In the exam you will be expected to trace, explain and write Java code that makes use of simple and
nested IF statements.
Or:
if ( num > 90 )
{
System.out.println( "You earned an A" ) ;
}
else
if ( num > 80 )
{
System.out.println( "You earned a B" ) ;
}
else
if ( num > 70 )
{
System.out.println( "You earned a C" ) ;
}
The initialization step is executed first, and only once. This step allows you to declare and
initialize any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
Next, the Boolean expression is evaluated. If it is true, the body of the loop is executed. If it is
false, the body of the loop does not execute and flow of control jumps to the next statement
past the for loop.
After the body of the for loop executes, the flow of control jumps back up to the update
statement. This statement allows you to update any loop control variables. This statement can
be left blank, as long as a semicolon appears after the Boolean expression.
The Boolean expression is now evaluated again. If it is true, the loop executes and the process
repeats itself (body of loop, then update step, then Boolean expression). After the Boolean
expression is false, the for loop terminates.
Example:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
The While Loop
This loop continues while a Boolean expression is true. There is no knowing how many times the
loop will be executed prior to run time. This loop might never be executed if the expression is false
at the start of the loop.
Example:
public class Test {
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
If instead of ‘x++’ the code said ‘x=x+y’ where y was another variable it may get to be bigger than 20
very quickly or slowly depending on the value of y. You would then have more or less executions of
the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute at
least one time.
do
{
//Statements
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in the
loop execute again. This process repeats until the Boolean expression is false.
Example:
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
1. The size of an array is fixed (static) when it is declared (as opposed to an ArrayList whose
size is dynamic i.e. changes at runtime). In this case you have problems with wasted space if
the whole of the array is not being used during runtime for most of the time. You have to
set the size of an array to the maximum that would possibly be needed to avoid ‘array out
of bounds’ errors. However they are easier to understand, implement and maintain from a
programmers viewpoint.
Example:
2. The array is declared as a static variable which means that the array belongs to the class not
the object just as static variables explained previously.
Unicode's success at unifying character sets has led to its widespread and predominant use in
the internationalization and localization of computer software. The standard has been implemented
in many recent technologies, including modern operating systems, XML, the Java programming
language, and the Microsoft .NET Framework.
See also: http://en.wikipedia.org/wiki/Internationalization_and_localization
OpenSource Movement
Open source software is made available for anybody to use or modify, as its source code is made
available. Some open-source software is based on a share-alike principle, whereby users are free to
pass on the software subject to the stipulation that any enhancements or changes are just as freely
available to the public, while other open-source projects may be freely incorporated into any
derivative work, open-source or proprietary. Open source software promotes learning and
understanding through the dissemination of understanding
Programmers who support the open source movement philosophy contribute to the open
source community by voluntarily writing and exchanging programming code for software
development. The term “open source” requires that no one can discriminate against a group in not
sharing the edited code or hinder others from editing their already-edited work. This approach to
software development allows anyone to obtain and modify open source code. These modifications
are distributed back to the developers within the open source community of people who are
working with the software. In this way, the identities of all individuals participating in code
modification are disclosed and the transformation of the code is documented over time. This
method makes it difficult to establish ownership of a particular bit of code but is in keeping with the
open source movement philosophy. These goals promote the production of “high quality programs”
as well as “working cooperatively with other similarly minded people” to improve open source
technologies
D4 (Higher Level Only) Advanced Program Development
Example:
p.setName(“Fred”);
p is the object reference. You cannot call the method without it.
D4.6 Construct algorithms that use reference Mechanisms
In the exam you will be expected to construct java code using this dot notation properly. Just like in
your IA.
A list is a generic ADT and usually comes with the following basic methods:
Add adds an element to the list, size returns the number of elements in the list, get returns an
element from the list but the element remains in the list, remove removes the element from the list
for ever. IsEmpty returns true if there are no elements in the list and false if the list contains
elements.
Lists can be indexed to allow the program to add and remove elements from specified positions in
the list.
Stacks can be visualised liked a stack of trays of plates. The first element added to the stack sits at
the bottom. The last one added is the first one to be removed. LIFO(Last In First Out). The add
method for a stack is usually called ‘push’ and the remove method is usually called ‘pop’.
Queues act like a queue of people. The elements are added to the end of the queue and removed
from the front. FIFO(First In First Out). The add method for a Queue is usually called Enqueue and
the remove method is usually called DeQueue.
Stacks
They need a pointer that keeps track of the head of the stack. This is because this is where we want
to add and remove elements from.
Uses
Used to Convert a decimal number into a binary number
function outputInBinary(Integer n)
Stack s = new Stack
while n > 0 do
Integer bit = n modulo 2
s.push(bit)
if s is full then
return error
end if
n = floor(n / 2)
end while
while s is not empty do
output(s.pop())
end while
end function
Towers of Hanoi
First implementation (using stacks implicitly by recursion) Not JAVA
#include <stdio.h>
void TowerofHanoi(int n)
{
// Preprocessor for moveAndShow.
for (int d = n; d > 0; d--) //initialize
tower[1].push(d); //add disk d to tower 1
moveAndShow(n, 1, 2, 3); /*move n disks from tower 1 to
tower 3 using
tower 2 as intermediate tower*/
}
Stacks are also used by the operating system to keep track of instructions and which to execute next.
Additionally, the are used to keep track of events in software use so that the undo button can be
used.
Queues
Queues need pointers to keep track of the head and tail of the queue (front and back) as we add to
the rear and take from the front.
Usage:
Imagine you have a web-site which serves files to thousands of users. You cannot service all
requests, you can only handle say 100 at once. A fair policy would be first-come-first serve: serve
100 at a time in order of arrival. A Queue would definitely be the most appropriate data structure.
Similarly in a multitasking operating system, the CPU cannot run all jobs at once, so jobs must be
batched up and then scheduled according to some policy. Again, a queue might be a suitable option
in this case.
Say you have a number of documents to be printed at once. Your OS puts all of these docs in a
queue and sends them to the printer. The printer takes and prints each document in the order the
docs are put in the queue, ie, First In, First Out.
In the situation where there are multiple users or a networked computer system, you probably share
a printer with other users. When you request to print a file, your request is added to the print
queue. When your request reaches the front of the print queue, your file is printed. This ensures
that only one person at a time has access to the printer and that this access is given on a first-come,
first-served basis.
Binary Trees
An ordered list of elements where elements of a lower number or letter are stored to the left of the
node and elements of a higher number or letter are stored to the right of the node. All binary trees
have a root node at the top of the tree. All searching starts at this point. Recursion is used to print
out the content of the nodes in the tree by considering each set of three nodes as a tiny binary tree
and then moving on.
You can traverse a tree pre-order, in-order, post-order see here
http://datastructuresnotes.blogspot.co.uk/2009/02/binary-tree-traversal-preorder-inorder.html
Usage:
Binary trees are very useful if you want to find something quickly because they are stored in order.
For this reason a binary tree can be used to efficiently store and retrieve unique keys which might
index a file for example.
See also:
http://www.starteractivity.com/ictlesson/computing/cpt1/stacks%20queues%20and%20trees.pdf
D4.15 Explain the importance of style and naming
conventions in code
When working on code, especially in a team it is very important to code in a certain way, to follow
coding conventions. These are things like starting class names with a capital letter and objects with a
little letter, using meaningful names for the fields and variables you are using, indenting the code,
inline annotation etc.
The main point is that code is read more often than it is written. If everyone codes in the same way
it becomes more easily read. This cuts down time on maintenance and reduces the chance of error
through misinterpretation. This in turn saves time, money and effort.
This point is even more important when working remotely i.e. away from your colleagues. You might
be working across the country or across the world. If everyone follows the conventions, code is easy
to read and update.