Steve Vickers: Introduction to Computer Science

Fundamentals of Computing: Introduction to Computer Science

Assessed coursework 1

This coursework is assessed for MSc students and counts for 5% of the module total. You should deliver your answers to the box outside School reception by 12.00 midday on Monday 5th November 2012.

Intercalated year (ICY) students are advised to do the exercise as unassessed coursework, because it gives some preparation for the exam. If you would like me to mark your work to give feedback, post it in the same box as the MSc students, but please write "ICY" clearly at the top.

The exercise concerns a Java method to calculate the magnitude of a vector. Suppose the components of the vector are stored as the elements a[0], ..., a[n-1] of an array a. (n can be found in Java as a.length.) Then the magnitude of the vector can be calculated as the square root (java.lang.Math) of
a[0]*a[0] + ... + a[n-1]*a[n-1]
This sum can be calculated using either a for-loop or a while-loop.

The exercise has the following parts.

1. (3 marks) Write a Java class Vector. It must include an instance variable a for the vector:

    private double[] a;

and a method to calculate the magnitude of a, with Javadoc and method declaration as follows.

    /** Magnitude of vector
     * Calculates the magnitude of the vector corresponding
     *   to the array a.
     * 
     * @return magnitude
     */
    public double magnitude(){

Apart from those, your class can contain anything you like. For instance, you might want to include a constructor and test methods.

Submit a printout of the Java source of your magnitude method in your answer.

2. (3 marks) Use javap to produce a disassembled version (bytecode mnemonics) of Vector. Submit a printout of the disassembled version of magnitude in your answer.

Then answer the following questions.

3. (4 marks) For each local variable in the stackframe for magnitude, what does it correspond to in the Java? (Note - the instance variable a is not a local variable in the stack frame.)

4. (8 marks) Which lines of the bytecode for magnitude correspond to which parts of your Java source?

5. (8 marks) For one complete iteration of the main loop in your magnitude method, explain what will be the contents of the operand stack at the end of each bytecode operation.

I have not shown you all the bytecode instructions, nor do I expect you to know them. You can look them up in the Java Virtual Machine Specification. Chapter 6 has a list of all the different instructions.

Feedback for exam

An exam question on this topic would be similar to parts 3, 4 and 5, based on Java and bytecode set out in the question. You will not be expected to remember names of bytecode instructions - a list of relevant ones will be provided.