EXAM November 2011, questions and answers PDF

Title EXAM November 2011, questions and answers
Course Java programming
Institution University of Cape Town
Pages 17
File Size 339 KB
File Type PDF
Total Downloads 24
Total Views 137

Summary

Download EXAM November 2011, questions and answers PDF


Description

Name: ______________________

Please fill in your Student Number and Name.

______________________ Student Number

: __________________________________

Student Number: ______________________

University of Cape Town ~ Department of Computer Science Computer Science 1016S ~ 2011

November Examination

** SOLUTIONS ** Question

Max

1

8

2

4

3

8

4

8

5

12

6

10

7

10

8

20

9

20

TOTAL

100

Marks

: 100

Time

: 180 minutes

Mark

Moderator

Instructions: a) Answer all questions. b) Write your answers in PEN in the spaces provided. c) Show all calculations where applicable.

Question 1: Instruction Execution Order [8 marks] (a) How many times does the while loop below execute for each of the different options for line 14? 11 int y = -3, x = 0; 12 while (x > y) 13 { 14 //insert code that alters the condition 15 if (x==11) 16

y=20;

17 x ++; 18 }//How many times did the loop execute?

i. Line 14

x+=2;

[2]

x *=2;

[2]

x +=5;

[2]

4 loops ii. Line 14 infinite iii. Line 14 2 loops (b) Write code to convert the while loop into a for loop. for (;x>y; x++)

[2]

Question 2 : Constructors and methods [ 4 marks] Study this code and answer the questions that follow. package test1; /** * Person.java * @author admin */ public class Person { public String name = "John"; private String address = "Cape Town"; double accountBalance = 1000000; // write a constructor for Person that name and address // can be plugged in } (a) Write a constructor for a Person that takes name and address parameters.

[2]

public Person(String name_, String address_) { this.name = name_; this.address = address_; } (b) After writing the above constructor, do you need to write an empty constructor (the default one) in order to create a default object? Explain your answer. [1] yes. When you write a new constructor the default one is inactive/overwritten. //default constructor public Person() { } (c) Write a method to set the address instance variable. public setAddress(String address_) { this.address = address_; }

3

[1]

Question 3 : Accessibility [8 marks] (a) Study this code and answer the questions that follow. Assume that the code is located in the same folder/directory with the Person class from the previous question. package test1; /** * Driver.java * @author admin */ public class Driver { public static void main(String arg[]) { // instantiate an object called john that // takes no parameter 1 2 3 4 5

System.out.println(john.name); System.out.println(john.address); System.out.println(john.accountBalance); } }

i. In Driver program, instantiate an object called john that takes no parameter at line #1.[1] Person john = new Person(); ii. Can line #3 be compiled? If yes, what is the output? If not, why not?

[1]

System.out.println(john.name); => John iii. Can line #4 be compiled? If yes, what is the output? If not, why not?

[1]

System.out.println(john.address); =>False iv. Can line #5 be compiled? If yes, what is the output? If not, why not?

[1]

System.out.println(john.accountBalance); => 1000000.0 (b) Study this code and answer the questions that follow. Assume that the code is located in the same folder/directory with the Person class from the previous question. package exam; /** * Driver1.java * @author admin */ public class Driver1 { 4

public static void main(String arg[]) { // instantiate an object called peter that has name // “Peter” and “Durban” 1 2 3 4 5

System.out.println(peter.name); System.out.println(peter.address); System.out.println(peter.accountBalance); } }

i. In Driver1 program, instantiate an object called peter that takes “Peter” and “Durban” as its name and address parameters respectively at line #1. [1] Person peter = new Person("Peter", "Durban"); ii. Can line #3 be compiled? If yes, what is the output? If not, why not?

[1]

System.out.println(peter.name); => Peter iii. Can line #4 be compiled? If yes, what is the output? If not, why not?

[1]

System.out.println(peter.address); => False iv. Can line #5 be compiled? If yes, what is the output? If not, why not? System.out.println(peter.accountBalance);=> False

5

[1]

Question 4 : Graphical User Interfaces [8 marks] Consider the Java program below and answer the questions that follow. import import import public {

javax.swing.*; java.awt.event.*; java.awt.*; class Xam extends JFrame implements ActionListener public static final int WIDTH=600; public static final int HEIGHT=400; public Xam() { setTitle("MYSTERY EXAM Q"); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 1 getContentPane( ).setBackground(Color.WHITE); setLayout(new BorderLayout() ); // 2 JLabel lab = new JLabel(".... HI - HERE I AM !"); add(lab,BorderLayout.CENTER ); JButton hi = new JButton("HI"); add(hi,BorderLayout.NORTH); hi.addActionListener( this ); // 3 JButton bye = new JButton("BYE"); add(bye,BorderLayout.SOUTH); bye.addActionListener( this );

} public void actionPerformed(ActionEvent e) { String s = e.getActionCommand(); // 4 if(s.equals("HI")) getContentPane().setBackground(Color.WHITE); if(s.equals("BYE")) getContentPane().setBackground(Color.BLACK); } public static void main(String[] args) { Xam w = new Xam(); w.setVisible(true); // 5 } } (a) Draw a diagram to show the GUI that results when this program is run.

[2]

half mark for each of the following in the drawing: draw the frame with title etc. a button on the top and on the bottom these buttons go right across the frame the hi message in the middle (b) What happens when the user presses the “BYE” button? background of centre pane changes to black hiding “hi” message

6

[1]

(c) Briefly state the purpose/effect of each of the statements numbered //1 to //5 above (i.e. say why it is there or what would happen if it was left out). [5] //1: because default without this is to hide the window on close, not exit //2: allows placement of items on top/bottom/left/right/middle (or: without this they are placed on top of each other so that only 1 thing is visible) //3: this object implements the listener interface to react to this button-press //4: extracts the string on the button (or: to know which button was pressed) //5: window appears on screen, with just the “new” it would be created but not shown

7

Question 5 : OOP [12 marks] (a) Briefly explain each of the following Java terms so that the difference between the terms in each pair is clear: i. super( ) and this( )

[1]

call default superclass constructor; call default constructor of this class itself ii. overriding and overloading

[1]

subclass redefines superclass method while keeping same signature; same class has multiple methods with same name but different signature iii. inheritance and polymorphism

[1]

when a subclass reuses the variables and methods of its superclass; associating different meanings with the same method name and using late binding (b) What 3 kinds of method are statically bound rather than dynamically bound? constructors, static and final methods (c) Consider the Java program below and answer the questions that follow. public class Result { Student stu; int votes; public Result( ) {votes = 0; stu = null; System.out.println("made result");} public String toString( ) {if (stu != null) return stu + "=" + votes; else return “?=” + votes; } // - - - other code not shown here public static void main (String[ ] args) { System.out.println(“A”); Result x = new Result( ); System.out.println(“B”); SRCresult ann = new SRCresult( ); System.out.println(x); System.out.println(ann); Result pam = new SRCresult( ); System.out.println(pam); } } class SRCresult extends Result { String party; public SRCresult( ) {party = "none"; System.out.println("made SRCresult");} public String toString( ) 8

[3]

{return super.toString( ) + " party:" + party;} public void SRCParty( ) {System.out.println(party);} } i. Give the exact output that would be generated by this program.

[2]

A MADE RESULT

[1/2]

B MADE RESULT

[1/2]

MADE SRCRESULT ?=0 ?=0 PARTY:NONE

[1/2]

MADE RESULT MADE SRCRESULT ?=0 PARTY:NONE

[1/2]

ii. Give a Java statement to safely call the SRCParty method of pam at the end of the main( ) method above. [1] if (pam instanceof srcresult) ((srcresult) pam).srcparty( ); iii. Give the Java code for a safe copy constructor for Result. public result ( result other ) { if ( other != null ) { if (other.stu == null) stu = null; else stu = new student (other.stu); votes = other.votes; } }

9

[3]

Question 6 : Abstract Data Types [10 marks] (a) The so-called “millennium bug” was a major problem for the software industry in the late 1990s. In numerous application programs and databases, each date was represented by a string of decimal digits: two digits for the day-in-month number, two digits for the month number, and two digits for the year number. For example, 31 December 1999 was represented “311299”, the leading digits “19” of the year number being implicit. Thus there was no means to represent dates after or before the twentieth century. In principle, the solution was simple: What was it? In practice the problem was enormous: why? [3] The solution was to change things so that the year would be represented with 4 four digits instead of two. [2] In practice the problem was complex because it meant changing every program in which the previous format was used. [1] Clear case of when abstraction is useful. [1] (b) What are the obligations of a class that implements a specific interface?

[2]

To implement an interface, a programmer must do two things. First, the phrase implements interface_name must be included at the start of the class definition. To implement more than one interface, the interface names must be separated by commas. The programmer must then implement all the methods listed in the definition of the interface. (c) Why is it not possible to instantiate a generic class or method as an array or linked list?

[2]

An array or a linked list is a container. Generic classes can only be instantiated with base types e.g. Character. (d) Give an example of a design pattern based on the divide and conquer principle to sort an array. [3] sorting patterns based on selecting a splitting value or parameter [1]. Example Quicksort or mergesort – show how divide and conquer technique would work to solve the sorting problem [2]

10

Question 7 : Linear Data Structures [10 marks] (a) Propose a method, based on the divide and conquer principle, to find the value of the smallest element in an array of n numbers. [2] A divide and conquer sorting algorithm that uses a “pivot” as a splitting criteria is a good way of solving this problem [1] The algorithm can recursively split the array into elements that are less than and greater than or equal to the selected pivot. Each recursion will focus on the half of the array that is less than the pivot instead of on the whole array. [1] (b) Give a pseudo-code algorithm or explain how you would apply the selection sort algorithm to order the following array of characters – E X A M P L E Remember that selection sort works by maintaining a sorted left half of the array. So at any point in time all of the elements to the left of the current sort position will be ordered incrementally. [4] Result A E E L M P X. [2] First step compare element in first position with elements in other position. Hold any element, smaller than one in first position, in a temporary variable called “min” and make a note of the position (index) of the element in the array. [1] When the end of the list is reached swap min value with element in position 1. Repeat the procedure for elements starting at position 2. Algorithm terminates when nth element is reached. [1] Algorithm steps on EXAMPLE: Step 1: Comparing E with other elements in array results in swap between A and E to give: AXEMPLE. Step 2: Comparing X with all elements after X results in swap with first E to give AEXMPLE Step 3: Comparison results in swap with last E to give: AEEMPLX Step 4: Comparison between M and other array elements results in swap between L and M to give AEELPMX Step 5: Comparison between P and other elements in array gives : AEELMPX Step 6 and 7: No swaps needed and array is finally sorted. (c) Examine the following piece of code and explain what it does. public class computesomething { private class Node { private char item; private Node next; public Node(char newItem, Node linkValue) { item = newItem; next = linkValue; } } 11

[4]

private int SIZE = 5; Node[] T; public computesomething() { T = new Node[SIZE]; for(int i=0; i O --> T --> Y --> E H[1] --> U --> A H[2] --> Q H[3] --> H[4] --> N -->I --> S

13

Question 8 : Ethics, Cyberlaw and Development [20 marks] (a) Carl is an experienced systems designer. He currently works for general purpose software and hardware company on a project for a prominent contractor to the South African Department of Defence. The project involves developing a system that monitors radar signals for incoming missiles and launches missiles to counter the threat when deemed necessary. Carl was initially reluctant but eventually agrees. His thinking was that if he does not do it, someone else will anyway. During his work he develops serious reservations concerning the safety of the system and its ability to make the fine distinction between missiles and small planes. It could retaliate automatically against small planes rather than the intended target of incoming missiles. He expresses this to his project manager who promptly dismisses the claim on the basis that he does not agree with the claim and that the project was already late. i. Carl feels he has a responsibility to do something more. What should his further actions be? [2] He should first approach his immediate superiors, then those above them and so go up the hierarchy in his company. Only if that does not work should he go public and “blow the whistle”. [2] ii. Assume that the project has been declared confidential and that the new proposed South African Protection of Information Bill has been passed. What would the likely consequences be for Carl if he proceeds with public disclosure of the issue in what he believes is the public interest? [4] Under the new protection of information bill he will be jailed if he goes public and he will have no recourse to a “public interest defence” in court. [4] (b) Jeremy Bentham, a Utilitarian philosopher, designed model prison called a “Panopticon”. i. What characterizes Utilitarian philosophy?

[2]

Everyone should act so as to bring about the greatest amount of happiness for the greatest number of people. Or the good ends justifies the means provided all people are counted equally. Or An action is right if it maximises benefits over costs for all involved, everyone counting equal. [2] ii. What was the underlying principle of human behaviour on which the “Panopticon” worked? [2] When people believe that they are being watched: they behave differently and they think of themselves as observer may think of them [2] iii. In today’s world we have closed circuit TV monitoring of public areas, we have mobile phone monitoring via the Regulation of Interception of Communications and Provision of Communication-Related Information Act (RICA), as well as voluntary visibility of private information on the internet (via blogs, Facebook and Twitter, for example). Discuss the extent that society is now an open prison based on panopticon design. Give arguments for and against. [6] 14

Open ended. For: Because of the surveillance of public spaces people do think they are being observed, that is the intention and so the behave differently and it reduces criminality. Criminals may also believe they are watched on phones etc. [3] Against: there is not really one central authority doing the watching. Also the internet is not so much surveillance as self disclosure. Even public monitoring merely replaces the informal social control that passersby would provide (if they are there) and this is not like being in a prison. [3] (c) What is “copyleft”? Say how it works in terms of copyright and what its intention is. copyleft uses copyright law [1] but for the opposite purpose to what it is normally used for [1]: it is a general method for making a program or other work free [1], and requiring all modified and extended versions of the program to be free as well.[1]

15

[4]

Question 9 : Healthcare Information Management System [20] The South African government has decided that all citizens should have access to their medical records, in keeping with the Promotion of Access to Information Act (2000). •

Information about a citizen includes: Name, Gender, Age, ID number, Address.



Each citizen can view his or her information but update only their address.



Medical records include: ID number, date, doctor; along with illness, notes and medicine (this is if the record is from a doctor) or injection, date, weight and pulse (this is if the record is from a clinic).



Each medical record belongs to a particular citizen who can be identified by ID number and a citizen can have any number of records.



The system can store and retrieve all information about the citizen. It can create a new medical record corresponding to each citizen. The medical record could either be a record from a doctor or a record from a clinic.



Given a correct ID number, a citizen can print their medical records.

Assume that all data is stored in a suitable data structure in memory while the program is running and then answer the following questions on this data structure. Hint: Read ALL the questions in this section before you begin to answer any of them as the design of your solution must address all the issues noted. (a) Draw a UML class diagram to illustrate all classes of the system and the relationships among them. In particular, i. Identify the classes (there are 3 classes).

[1]

ii. Draw a full class diagram for only one class.

[2]

iii. Draw the relationship among the 3 classes.

[2]

(b) Discuss the classes and the relationships between them in terms of satisfying the requirements of professionally produced software according to accepted codes of practice? [5] The answer depends on an appreciation of the issues covered in the CSSA or BCS code of practice. We do not expect students to memorize these but they do need to be able to recognize important issues. Basically a single mark will be given for every correct statement. Given the slant of the question most would fall under the headings of Privacy, Security and Integrity. But other possibilities are not excluded. So as an example a good answer would include the following (Max 5!): Medical records contain sensitive personal information so a number of the classes included in the design deal with privacy, security and data integrity concerns [1]. The system will also comply with relevant...


Similar Free PDFs