OU M257 Revision notes

Next week I’m sitting an Open University exam on the Java course M257.  I’ve made some notes on most of the units which you can see below:

Unit 3

  • Implement classes in which you have specified the access level of methods and instance variables;
  • private access level: never inherited, so can never be accessed by subclasses as if they were part of the subclass.
  • Public access level: If you precede an instance variable or a method of a public class with the keyword public, then any class can access that member using a reference and a dot notation. Any public members are inherited by all subclasses, so they can be accessed within those classes without a dot notation.
  • Protected access level: available only to classes in the same package. Any subclass inherits any protected and public members of its superclass.
  • Understand the difference between instance variables and class variables, and be able to decide when to use each;

Instance variables are defined in the class above the constructor. Values relates to that object. Class variable are defined as static, only one copy of the ‘variable’ is created for all instances of the class. Reasons to use class variables:

  • Constants: A common use is to define some constant associated with the class. For example, the Java package associated with mathematical processing implements the mathematical constant PI in this way.
  • One value for all objects: A second use of class variables and methods is to implement data that has only one value for every object of that class. One common example of this is to keep count of the number of objects of a class type that have been created. It might lead to errors if each object kept its own version of this count, as each object would have to update the count every time a new object came into existence and it would be easy to forget to update some object’s copy of this variable.

private int numOfSpots; //instance variable

private static int numOfLegs; //class variable

Often but not always static variables are constants. To declare a variable as a constant the keyword final is used and for readability the name is in CAPS

static final int MAX_VALUE = 12;

Methods can also be declared as static. If you try to access a nonstatic variable from a static method then you will get a syntax error.

  • Write constructors for classes;

Constructor is a method with the same name as the class. Multiple constructors can exist for the same class if they have different arguments. A constructor sets the default variable values. The constructor of the superclass can be called in a constructor using super(); if it has zero arguments. Otherwise arguments can be pass to the superclass constructor like this.

public FourInt (int a, int b, int c, int d)

{

super(a, b, c);

s = d;

}

  • Use inheritance to develop new classes;

To inherit from a class the class header needs to include the keyword extends followed by the class name.

public class PrivilegedUser extends User

  • Discuss the nature of the Java class hierarchy and the purpose of the Object class as the root of this hierarchy;

All Java classes inherit from the object class as it is at the top of the hierarchy. The object class therefore has no superclass.

  • Write an equals method for a class;

By default the equals method compares object references not object contents.

Writing another equals method means we can compare contents as well.

public boolean equals (User u) // this method overloads the equals method.

{

return userID.equals(u.userID); // compares if userID’s are the same.

}

public boolean equals (User u) // this method overloads the equals method.

{

return userID.equals(u.userID) && emailAddress.equals(u.emailAddress) &&               numOfAccesses == u.numOfAccesses; // compares userID’s, emails and number of accesses.

}

public boolean equals (Object o) // this method overrides the equals method

{

// cast the Object argument to a User type

User u = (User) o;

return userID.equals(u.userID);

}

Use like this: emma.equals(maria);

  • Write a toString method for a class.

toString class by default returns class name followed by @ followed by a by a numeric hexadecimal value. To make a more useful toString class override method returning more useful info from constructor for example.

public String toString ()

{

return “User ” + userID + “, Email ” + emailAddress;

}

To use a toString method. Call println on an object.

User a = new User(“Tembo”, “zamby@lusaka.zm“);

System.out.println(a);

produces the output: User Tembo, Email zamby@lusaka.zm

Unit 4

Explain the concept of a stream;

A stream for providing its input/output facilities. A stream, sometimes referred to as a byte stream, is essentially a sequence of bytes, representing a flow of data from a source to a destination. This includes the keyboard, screen and various sorts of data files, as well as between networked computers. They also allow manipulation of the data on the way: for example, by converting the data to different formats or by storing it temporarily (buffering).

Use the basic Java facilities for input and output;

//Read from Keyboard

public void hello()

{

Scanner sc = new Scanner(System.in);

//Ask what is your name

String name = sc.nextLine();

//Ask what is your age

int age = sc.nextInt();

//Display name and age here

sc.close();//take care

}

//Read from a file

public void hello()

{

Scanner sc = Scanner sc = new Scanner (new File (“source/use.txt”));

//Ask what is your name

String name = sc.nextLine();

//Ask what is your age

int age = sc.nextInt();

//Display name and age here

sc.close();//take care

}

//Read from a datafile.

FileInputStream fis = new FileInputStream(“payroll.dat”);

DataInputStream dataIn = new DataInputStream(fis);

//Output to text file

Public void hello()

{

PrintWriter pw = new PrintWriter(“Hello.txt”); //creates new file

pw.println(“The first line”);

pw.println(“The second line”);

pw.close();

}

//output to datafile

FileOutputStream fos = new FileOutputStream(“payroll.dat”);

DataOutputStream dataOut = new DataOutputStream(fos);

Distinguish text input/output from binary input/output;

  • Text input/output: human readable using a simple text editor or word processor.
  • Binary Input/Output: machine readable, more efficient.

Identify when it is appropriate to use exceptions;

If the code within a method may throw a checked exception, then you must do one of two things:

  • Declare in the method header that an exception may be thrown. in this case you do not handle the exception within the method, but simply pass it on;
  • Catch the exception and deal with it within the method, using a try-catch statement.

Distinguish between checked and unchecked exceptions;

Examples of checked exceptions.

  • EOFException occurs when a program attempts to read past the end of a file.
  • FileNotFoundException can occur when a program attempts to open or write to an existing file. If the file cannot be found, then this exception is thrown.
  • MalformedURLException indicates that an invalid form of URL (such as a website address) has occurred.

Examples of unchecked exceptions, as they are subclasses of RunTimeException.

  • ArrayIndexOutOfBoundsException occurs when a program tries to access an array with an index outside the valid limits.
  • ArithmeticException arises when an illegal arithmetic condition occurs, such as an attempt to divide an integer by zero.
  • NumberFormatException can be caused by an application expecting to read a number of some sort, when the data does not have the appropriate format.
  • NullPointerException happens when an application attempts to use null in a case where an object is required: for example, invoking a method on a null reference.

Define and use new types of exception;

DEFINE

class FileFormatException extends IOException

{

private int errorPosition;

public FileFormatException () {}

public FileFormatException (String message, int bytesRead)

{

super(message);

errorPosition = bytesRead;

}

public int getErrorPosition ()

{

return errorPosition;

}

}

USE

try

{

// code to be checked

if (checkFormat(theNewFile))

{

}

}

Catch (FileFormatException exception)

{

String reason = exception.getMessage();

int errLoc = exception.getErrorPosition();

System.out.println(reason+” at “+errLoc);

}

Deal with error conditions in a Java program, by means of exceptions or otherwise;

public void loadFiles ()

{

Try

{

If (checkFormat(“File1.dat”))

{

// code to process file data

}

}

catch (EOFException eofEx)

{

// code to handle this exception

// eofEx refers to EOFException object

}

}

Use the StringTokenizer class to split string data into substrings.

String = new String(T.F.Jones@coolmail.com Tom Jones);

StringTokenizer em = new StringTokenizer( eMailAddress, “@.”);

while (em.hasMoreTokens())

{

System.out.println(em.nextToken());

}

OUTPUTS:

T

F

Jones

Coolmail

com Tom Jones

Defensive programming.

The defensive programming style of coding is appropriate for certain kinds of common error conditions. However, it has some drawbacks:

  • If there is a lot of error checking and handling code, this can obscure the main purpose of the method;
  • It is somewhat ad-hoc – different programmers or Java library code may take different approaches to signaling or handling errors;
  • Some serious errors cannot easily be handled within the method where they occur – they may need to be passed to higher level code;
  • It may not be possible for a method to return a value indicating that an error has occurred – for example, if the method already returns a result.

Unit 5

Use library classes from the standard Java packages;

First import them.

Import java.util.*; // The * means that the whole contents of java.util is available to use.

java.util and java.sql both contain a class called date. To use the date class from java.sql we can include an import at the top of our classes like below. Otherwise well get a name clash that will not compile.

Import java.util.*;

Import java.sql.*;

Import java.sql.Date;

You never need to import java.lang

Broadly understand the contents of the java.util package;

1.       Contain Java Collection Framework: LinkedList, ArrayList, HashSet, TreeSet, HashMap and TreeMap

2.       ‘Legacy’ collection classes

3.       Random class

4.       StringTokenizer class

Use some of the important collection classes provided within the java.util package;

HashSet

Set<Integer> s= new HashSet<Integer>(); Using the Set interface.

if (s.isEmpty())

{

System.out.println(“Set initiallyempty”);

}

s.add(23);

s.add(25);

s.add(11);

// three integers added

System.out.println(“The set has ” + s.size() + “elements”);

s.remove(23);

// there are nowonly two integers in the set

System.out.println(“The set now has “+ s.size() + “elements”);

LinkedList

LinkedList<Integer>numList =new LinkedList<Integer>();

numList.add(99);

numList.add(103);

numList.add(88);

// there are now three items in the list

System.out.println(“First item is “+numList.getFirst());

System.out.println(“Lastitem is “+numList.getLast());

ArrayList

ArrayList <Integer> holder = new ArrayList <Integer>();

holder.add(3);

System.out.println(holder.remove(0)+2); //returns 3 then adds on 2

HashMap

HashMap <String,String> hm =new HashMap<String, String>();

System.out.println(“Hello there”);

hm.put(“Dave”,” London “);

hm.put(“Robert”, ” Sheffield “);

hm.put(“Darrel”, ” Milton Keynes “);

System.out.println(“Darrelisassociated with “+hm.get(“Darrel”));

for(String name: hm.keySet()) // The code hm.keySet returns the collection of keys associated with hm.

{

System.out.println (name+” is associated with the city “+hm.get(name));

}

Define your own packages for structuring large programs;

To define a collection of classes as a package, you need to precede the source code of each of the classes with the keyword package followed by the name of the package, as follows:

package testPackage;

  • * explain the role of the Object class in heterogeneous collections;
  • * explain the concept of an interface and its role in relation to multiple inheritance;

An Interface is like a class that has method headers but very little method bodies. An interface declares what has to be done but not how to do it. Interfaces do not contain variables but can contain constants. Interfaces are not classes.

publicinterface Comparable<T> //T is the type being compared.

{

int compareTo(T o); // method header only in this example there are no constants defined. Methods in interfaces are know as abstract methods.

}

A class that implements the above class start like this and must contain a method called compareTo.

class Employee implements Comparable <Employee>

Understand the concept of an abstract class;

Abstract classes are useful in defining groups of classes related by inheritance. Abstract classes normally have at least one abstract method. An abstract method has header, but has no implementing code associated with the header. The implementation code must be supplied by subclasses of the abstract class. The keyword also used to identify these methods. Note the difference from interfaces, which have abstract methods but do not require the word abstract in the declaration.

  • cannot be instantiated;
  • may have instance variables, finals, static variables and concrete methods.

An abstract class may be useful because:

  • it can be used to factor out common features of a number of classes, which then

inherit from the abstract class and implement or override methods as required;

Abstract methods

1.       Boolean hasNext() – returns true if the iteration has more elements

2.       E next() – returns the next element in the iteration

3.       Void remove() – removes from the underlying collection the last element returned by the iterator (optional operation)

use polymorphism in connection with abstract classes;

If Employee is an abstract class of WeeklyEmployee and MonthlyEmployee and both contain a different method called payment. When staff is an instance of Employee we can call either of the payment methods like this.

staff.payment();

If the staff object is a WeeklyEmployee it will use its class, if the object is MonthlyEmployee it will use the payment method of the MonthlyEmplyee class. This is polymorphism.

Contrast interfaces and abstract classes;

Interface:

1.      An interface is not a class.

2.      All its methods are abstract and, apart from its abstract methods, it may contain only constants. The methods are implicitly treated as abstract and the constants are treated as if declared as public static final.

3.      An interface can be implemented by any number of unrelated classes, which declare this using the implements keyword. A class may implement any number of interfaces.

Abstract class:

1.      An abstract class uses the keyword abstract in the class header.

2.      It normally has at least one abstract method, either defined within the class or inherited from a superclass, and its abstract methods must be explicitly declared abstract. It can also have concrete methods (that is, it may be fully implemented) and instance variables, unlike an interface.

3.      It can only constrain its own concrete subclasses, by requiring them to implement its abstract methods – it cannot constrain any other classes.

The similarities between an interface and an abstract class in Java:

1.      They can both place requirements on objects of other classes.

2.      Both can have abstract methods (although neither need have abstract methods).

3.      You cannot create objects of an abstract class type or an interface type. You can,

4.      however, create reference variables of either type. These are normally used to refer to an object of a subclass of the abstract type or to an object of a class that implements the interface, respectively.

5.      Both can inherit: the abstract class from another class; the interface only from another interface.

Use the Iterator interface defined for Java collection classes.

Example

ArrayList<String> userList =new ArrayList<String>();

Iterator <String>listIt =userList.iterator();

System.out.print(“The list is [");

while (listIt.hasNext())

{

System.out.print(listIt.next() +" ");

}

System.out.println(" ]“);

Unit 6

GUI element need a JFrame, class extends JFrame.

Buttons:

JButton offButton = new JButton( ); // unlabeled

JButton onButton = new JButton(“Cancel”); // labeled

offButton.setText(“Press Me”);  // set label

String offButtonLabel = offButton.getText( ); // name a variable the label of an exciting button

Labels:

JLabel testLb = new JLabel(“Verbose Interface Cluster”);

testLb.setText(“Good Bye”);

Check Box:

JCheckBox noviceUserType = new JCheckBox(“Novice”); // labeled Novice state is true or false

boolean b = noviceUserType.isSelected( ); // will set b to true or false

Radio Buttons:

// first create the button group

ButtonGroup language = new ButtonGroup( );

// then create the buttons

JRadioButton frenchButton = new JRadioButton(“French”, true);

JRadioButton englishButton = new JRadioButton(“English”, false);

// then add the buttons to the button group

language.add(frenchButton);

language.add(englishButton);

Combo Box:

JComboBox computerChoice = new JComboBox( );

computerChoice.addItem(“PC”);

computerChoice.addItem(“Mac”);

computerChoice.setSelectedItem(“Mac”); // default Variable

Text Fields:

JTextField txtA = new JTextField( ); // default

JTextField txtB = new JTextField( 24); // 25em width

JTextField txtC = new JTextField(“Text Field Type here”); // default contents

JTextField txtD = new JTextField(“This is for typing”, 20); // default contents and width

Text Areas:

JTextArea ta = new JTextArea (“This is some text to start off with. \n” +

“Do you like it ? yes or no ?”, 4, 20);

// same as text field but has has extra argument for box length.

Scroll bars:

JScrollBar scbV = new JScrollBar(JScrollBar.VERTICAL);

JScrollBar scbH = new JScrollBar(JScrollBar.HORIZONTAL);

Menu bars:

JMenuBar mb = new JMenuBar( ); // new menu bar

JMenu m = new JMenu(“File”); // new menu section

m.add(new JMenuItem(“close”)); // new menu item in section

m.add(new JMenuItem(“save”)); // new menu item in section

mb.add(m); // add menu section to bar

setJMenuBar(mb); // set bar

Layout FlowLayout: Default

/ * Place some buttons. */

Container cp = getContentPane( );

cp.setLayout(new FlowLayout( ));

Layouts: GridLayout:

/ * Place some buttons. */

Container cp = getContentPane( );

// set size of grid – rows then columns

cp.setLayout(new GridLayout(3, 2)); // 3 tall by 2 wide grid.

Layout BorderLayout:

/ * Place some buttons. */

Container cp = getContentPane( );

cp.add( buttons [0 ], BorderLayout.NORTH);

cp.add( buttons [1 ], BorderLayout.SOUTH);

cp.add( buttons [2 ], BorderLayout.EAST);

cp.add( buttons [3 ], BorderLayout.WEST);

cp.add( buttons [4 ], BorderLayout.CENTER);

Class to display your code

public class FrameDemoTest

{

public static void main (String [] args)

{

FrameDemo fd = new FrameDemo(“We Love Java”);

fd.setVisible(true);

}

}

Unit 7

Work within an event-driven programming environment;

Non linear. Event-driven programs are programs that respond to events initiated by the user, such as mouse clicks and key presses. Events can also be initiated through software coding, using for example the Timer class,

Attach code to visual components to capture user input in the form of events such as mouse presses and text input;

FOR A BUTTON

buttonUp = new JButton(“Press Me Up”); // define a new button buttonUp.addActionListener(new ButtonWatcher()); // attaches ActionListener to button

/* Define the listener inner class implementing the interface ActionListener. */

private class ButtonWatcher implements ActionListener

{

/* Here is the code which is executed when the button is clicked. Note the class implements */

public void actionPerformed (ActionEvent a)

{

Object buttonPressed =a.getSource();

if (buttonPressed.equals(buttonUp))

{

buttonClicks++;

}

if (buttonPressed.equals(something else))

{

buttonClicks–;

}

label.setText(buttonClicks + “”);

}

}

FOR A MOUSE CLICK etc…

c = new JPanel();

c.addMouseListener(new MouseEventer()); // attaches MouseListener to previously define panel called c.

/* Define the listener inner class implementing the adapter class

. */

private class MouseEventer extends MouseAdapter

{

/* Here is the code which is executed when the mouse is clicked. Note the class extends */

public void mouseClicked (MouseEvent a)

{

int xCoordinate = e.getX();

int yCoordinate = e.getY();

yCoordLabel.setText(yCoordinate + “” );

xCoordLabel.setText(xCoordinate + “” );

}

}

Use inner classes;

Inner classes are nested inside of normal classes. advantages of using inner classes is that the inner class has access to all of the methods and data fields of the surrounding class.

Create simple animations;

One class sets up panels/window/frame that animation happens in. paint method is overridden.

public void paint (Graphics g)

{

super.paint(g);

myBall.paint(g);

}

// class contains move method that trigger another move methods in another class.

public void move ()

{

while (true)

{

myBall.move(); // not yet defined

repaint();

try

{

Thread.sleep(50);

} catch (InterruptedException e)

{

System.exit(0);

}

}

}

class that  builds object above calls move method of above.

public class MovingBallTest

{

public static void main (String[]args)

{

MovingBall world = new MovingBall(“Moving Ball”);

world.setVisible(true);

world.move();

}

}

another class in this case called ball must include it own paint method and move method. Move method should contain code to change size, direction, shape, speed, coordinates etc…

Use the graphical facilities within Java.

Here we override the method paint to create what we want to appear on screen. */

public void paint (Graphics g)

{

super.paint(g);

g.drawRect(50, 50, 100, 75);

}

With shapes the first 2 variables are the distance in pixels from the top left corner of the window/panel.

topleft at (x, y)

Rectangle testRectangle = new Rectangle(x, y, width, height);

Fonts example

public void paintComponent(Graphics g)

{

Font someFont = new Font(“Serif”, Font.BOLD, 12);

g.setFont(someFont);

g.drawString(“Some Text!”, 50, 50); // draws, some Text! 50×50 from top left in bold serif font

FontMetrics someFontMetric = g.getFontMetrics(someFont);

int wordLength = someFontmetric.stringWidth(“Hello”); // gives length in pixels of the graphic word Hello

}

assigned an image to a variable

private Image picture = null;

picture =getToolKit().getImage(“mypicture.gif”);

g.drawImage(picture, 0, 0, this);

Unit 8

Understand how threads can help to make more effective use of a computer’s resources;

Threads are not the actual static code itself but rather they are the dynamic process of executing that code. The threads share the CPU, the operating system will allocate small blocks of time to each thread.

Define, create and use threads;

Define

Create

public class WhereAmIRun extends Thread

{

int thisThread;

// constructor

public WhereAmIRun (int number)

{

thisThread = number;

}

// implement the run method

public void run ()

{

for (int i =0;i< 100; i++)

{

System.out.println(“I’m in thread ” + thisThread);

}

}

}

You can also use the Runnable Interface which allows classes to inherit from more than just the threads class. The runnable inferface has one method called run. The creation of a threadable class is the same as defined above but has a slightly different first line.

public class WhereAmIRun implements Runnable

USE

public class ThreadTester // for classes that extend the Thread class

{

public static void main (String [] args)

{

// create the threads

WhereAmI place1 = new WhereAmI(1);

WhereAmI place2 = new WhereAmI(2);

WhereAmI place3 = new WhereAmI(3);

// start the threads

place1.start();

place2.start();

place3.start();

}

}

public class ThreadTesterRun // for classes that use the runnable interface we need to create thread objects

{

public static void main (String [] args)

// create a runnable object

WhereAmIRun place1 = new WhereAmIRun(1);

// now create a thread to run it

Thread thread1 = new Thread(place1);

// repeat for two further objects

WhereAmIRun place2 = new WhereAmIRun(2);

Thread thread2 = new Thread(place2);

WhereAmIRun place3 = new WhereAmIRun(3);

Thread thread3 = new Thread(place3);

// start the threads

thread1.start();

thread2.start();

thread3.start();

}

}

Describe the various states that threads can be in;

A thread is in one of five states at any moment in time. These are:

1. initial state;

2. runnable state;

        • ready to be used by the JVM

3. running state;

4. blocked state;

        • it is waiting for an I/O process to complete;
        • some other part of the program has not completed its processing;
        • it is not being given access to some shared data.

5. finished state.

Appreciate some of the problems that can occur when threads access shared resources;

Multiple threads accessing shared resources can cause problems as they can block each other, or change variables that other threads are relying on.

Understand how locks affect the execution of code.

Threads can lock a shared resources to avoid problems. To do this any thread methods that access shared data need to be defined with the static variable, synchronized (with a ‘Z’). This stops any other threads using this method and put them in the blocked state until the resource is unlocked. To prevent the locking of shared resources creating new potential problems follow points.

  • If two or more threads modify a common object, then declare the methods that do the modifying as being synchronized.
  • If a thread needs to wait for an object to change, make sure that it waits inside the thread. It does this by entering a synchronized method and calling wait.

When a method has changed an object, it should call the notify method or the notifyAll method before terminating. This gives other methods a chance to access the object. notifyAll(); or notify();

2 Comments

    Great help for my last minute cramming.

    Cheers

  • I’m sure viagra is one of the betst pills for men

Leave a Reply




Popular Topics: iPod For Sale OU Open University M257 iPod Touch WordPress Apple App Store firmware red dwarf iTunes Window Format Photo House Creative Commons Flickr PHP Geek Delivery Sofa OSX Mac Chris Ford TV lesson Sci Fi xbox vertical lines iMac rant xbox live links internet speed email play.com faster fieldrunners gaming google Bill Bryson science book