Specimen paper

advertisement
There are three appendices at the end the of the paper. Appendix
A contains some useful Java APIs. Appendix B contains the
description of a JSP object. Appendix C contains some constructs
used in XML schema. Please write down your answers in the
answer book.
Part I. Answer all questions in this part. This Part consists of 55%
of the total marks.
Question 1
[5 marks]
State whether each of the followings is true or false about Java:
(a)
Java has no reserved words.
[1]
(b)
In a Java class, a static method and a non-static method can have the same signature.
[1]
(c)
In a Java class, an attribute can have the same name as a method .
[1]
(d)
In a Java for loop, the loop counter can be explicitly changed to any value .
[1]
(e)
In Java, object parameters are passed by reference in calling a method.
[1]
Question 2
[6 marks]
A shop provides two kinds of membership cards to its customers. Gold members are entitled to
10% discount on all sales. Silver card members are entitled to 5% discount. Gold members
receive two bonus points on every dollar spent in the shop. Silver members receive one bonus
point on every dollar spent. They can use the bonus points to buy special offered items. Now,
you need to write three classes Member, GoldMember, SilverMember to model memberships of
the shop. The Member class should have one attribute to record the bonus points of the
member. GoldMember and SilverMember are subclasses of Member. In Member, you need to
define the following methods:

int discount(): this method returns the discount that the member can enjoy.

int bonus(): this method returns the number of bonus points that the member has.
COMPS311(1315)
Page 2 of 15

int bonusPerDollar(): this method returns the number of bonus points for one dollar spent.

float buy(float xxx): this method is called when the member makes a purchase of $xxx. It
returns the amount after the discount and record the bonus points resulting from this
purchase. The number of bonus points are truncated to integers. If xxx is 150 and the
discount is 5%, it should return 142.5(150*0.95=142.5) and the internal bonus point
attribute should be increased by 142.
Note that some of the methods in Member are abstract and therefore the Member class should
be abstract. Write down the three classes.
Question 3
[5 marks]
Write a java program that reads from two files concurrently. The two files contain integers that
have been written to them using the writeInt method in DataOutputStream. The program
should count the total number of positive integers(greater than 0) in the two files.
The command to execute the program is this:
java CountPositive c:\file1.dat c:\file2.dat
The output looks like this:
There are 203 positive integers in the two files.
No marks will be awarded to answers that read the two files one by one. You have to use two
threads to read the two files concurrently.
[You need a synchronized method to record the number of active threads. The output will only
be printed when both reading threads have stopped]
Question 4
[6 marks]
(a)
List two advantages of enforcing information hiding.
[2]
(b)
Briefly explain how Java enforces information hiding.
[4]
COMPS311(1315)
Page 3 of 15
Question 5
[6 marks]
Write a Java class which models a lock to a door. The lock can only be unlocked when two
different users involve the unlock method of the lock. If only one user involves the unlock
method, then he has to wait until the other person also involves the unlock method.
The class looks like this:
public class TwoPersonLock {
.... //attributes of the class
public synchronized void unlock(int userid) throws SameUserException,
NotLockedException {
....
}
public synchronized void lock(int userid) throws NotAllowedException {
....
}
}
When a user invokes the unlock method, he will pass his user id as a parameter. If at this
moment only no other person calls this method, he has to wait until another user calls the same
method. If the same user calls the method twice, the SameUserException will be thrown. If the
lock is not actually locked when this method is called, the NotLockedException is thrown.
Once the lock is locked, it can only be unlocked by one of the two users who unlocked it last
time. This is checked when a user calls the lock method with his user id. The
NotAllowedException will be thrown in two cases:

the lock is already locked.

the one invoking this method is not the one of the two users who have just unlocked it.
You need to provide the definition of the class. You can assume that the 4 exception classes
have been defined for you with default constructors.
COMPS311(1315)
Page 4 of 15
Question 6
[5 marks]
A database contains information regarding students and courses studied in a university.
Student (Information of students)
Attribute
Name
StudentID
Address
Data type
varchar(50)
varchar(10)
varchar(100)
Study (Study records of students)
StudentID
CourseID
Grade
varchar(10)
varchar(10)
varchar(2)
Course (Information of courses)
CourseID
Title
varchar(10)
varchar(50)
Complete the following JSP that displays the student records of a particular course. The id of
the course should have been passed as the parameter named courseid.
<%
Class.forName("com.mysql.jdbc.Driver");
String url =
"jdbc:mysql://192.168.62.100:3306/2014exam";
java.sql.Connection con = java.sql.DriverManager.getConnection(url, "comps311f3",
"comps311f3");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Course records</title>
</head>
<body>
<%
// your code here
%>
</table>
</body>
</html>
COMPS311(1315)
Page 5 of 15
The following example shows the content when the request URL is:
http://localhost:8080/web/index.jsp?courseid=COMPS311.
Only 3 students have studied this course. The title of the course is Java Application Development.
Question 7
(a)
[5 marks]
State two advantages of pass-by-reference over pass-by-value in passing parameters in
calling subprograms.
(b)
[2]
Java passes all parameters by value while C++ can passes parameters by value or
reference. Compare this feature of the two languages in terms of readability. Explain
your answer.
Question 8
[3]
[5 marks]
Consider the following DTD file:
<!ELEMENT Book(title,author+,chapter+)>
<!ELEMENT title(#PCDATA)>
<!ELEMENT author(firstname,lastname)>
<!ELEMENT firstname(#PCDATA)>
<!ELEMENT lastname(#PCDATA)>
<!ELEMENT chapter(#PCDATA)>
Convert the DTD file into an XML Schema.
COMPS311(1315)
Page 6 of 15
Question 9
[6 marks]
Assume that you are designing a new programming language. For each of the following
constructs of the language, list one feature you would like the language to have that would
increase the readability of the language.
(a)
the if statement.
(b)
the switch statement.
(c)
subprogram calling.
COMPS311(1315)
Page 7 of 15
Question 10
[6 marks]
State the problem in each of the following Java code fragments.
(a)
(b)
(c)
(d)
(e)
(f)
...
Thread th=new Thread() {
public void run() {...}
};
th.run(); //start a thread
...
...
int i;
if (a==4) {
i=3;
}
callMethod(i);
...
...
public static void swap(int a, int b) { // swap the two
//parameters
int tmp=a;
a=b;
b=tmp;
}
...
swap(x,y); //call the method to swap the values of x and y
...
public interface ABC {
public void abc() {System.out.println("hello");}
}
public class ABC {
abstract void abc();
}
public double average(int num[]) {
//this method is used to calculate
//the average of the integers in num
int sum=0;
for (int i=0;i<num.length;i++) {
sum+=num;
}
return sum/num.length;
}
[End of Paper I]
COMPS311(1315)
Page 8 of 15
Part II. Answer any THREE of the questions. Each question carries
15% of the total marks.
Question 11
(a)
[15 marks]
Compare pointers and references in terms of readability, writability and reliability.
Explain your answer.
(b)
[4]
Write a multithreaded Java server which has the following properties:

It listens to requests at port 12345.

When a request arrives,
o
it creates a new thread to serve the request.
o
the client first sends to the server a string representing the client's name.
o
then the clients will send in a number of strings. For each of these strings,
the server will check whether the string corresponds to a connected client's
name. It will return a string of 'yes' or 'no' to specify whether the name
represents a connected client.
o
the client will finally disconnect from the server by closing the socket at the
client side.
You only need to implement the server, not the client.
[Hint: you need a data structure to store the names of connected clients. You need a
synchronized method to check if a string corresponds to a connected client. You do not
need synchronized methods to remove or add a name to the data structure if the data
structure is thread safe. You need to add the name to the data structure when a client is
connected and remove it when he is disconnected.]
COMPS311(1315)
[11]
Page 9 of 15
Question 12
(a)
[15 marks]
Compare the readability, writability and reliability of two languages A and B in the
following aspects:
(i)
In A, only integers can be used as array index. In B, both integers, enumerated
types can be used as array index.
(ii)
(b)
In A, there is no goto statement. In B, there is goto statement.
[4]
Use RMI to write a peer-to-peer social network. Each user is represented by the interface
User
public interface User extends Remote {
public void addFriend(User user) throws RemoteException;
public void sendMessage(String st) throws RemoteException;
}
The addFriend method is used when a user wants to add another user as friend. The
former will invoke the addFriend method of the latter and pass himself as a parameter in
the method.
If a user wants to send a message to another user, the former will invoke the
sendMessage method of the latter with the message as the parameter.
The implementation of the interface looks like this:
public class UserImp extends UnicastRemoteObject implements User {
//attributes...
//additional methods to be invoked by the local user
public String readMessage() {.....}
public void sendToAllFriends(String message) {....}
}
readMessage and sendToAllFriend are two methods called by the local user.
When a remote user invokes the addFriend method, it will store the friend in a data
structure. UserImp should also have a data structure to store messages from remote
users. So if a remote user invokes the sendMessage method, the message will be stored.
The readMessage method is invoked by the local user to read the messages stored. It will
return the oldest message and delete it from the data structure. If there is no stored
COMPS311(1315)
Page 10 of 15
message, it will return null. The sendToAllFriends is used by the local user to send a
message to all his friends.
Provide the implementation of UserImp. Make sure your code is thread safe.
[11]
Question 13
(a)
[15 marks]
Consider the following C code:
int a=3;
void fun(int i) {
static int b=4;
a=b+i;
b*=4;
}
Write down whether each of the followings is done during language design time,
language implementation time, compile time, load time, link time or run time.
(i)
The address of a is fixed.
(ii)
The meaning of int is fixed.
(iii)
The address of fun is fixed.
(iv)
The address of b is fixed.
(v)
The address of i is fixed.
[5]
(b)
Give one example of polymorphism in Java without dynamic binding.
[3]
(c)
In C there are global variables. In Java, there are no global variables. What can you use
in Java that are similar to global variables in C? Compare the readability of global
variables in C and the entities you use which is similar to global variables. Explain your
answer.
COMPS311(1315)
[7]
Page 11 of 15
Question 14
(a)
[15 marks]
Can the use of a message authentication code(MAC) provide each of the following
features of the message?
(b)
(i)
confidentiality.
(ii)
integrity.
(iii)
authentication.
(iv)
non-repudiation.
[4]
Can the use of a secret key encryption provide each of the following features of the
message?
(c)
(i)
confidentiality.
(ii)
integrity.
(iii)
authentication.
(iv)
non-repudiation.
[4]
Write the following two programs, one for encrypting a file, the other for decrypting. The
encryption program works like this:
java EncryptFile keyFile inputFile outFile
keyFile is a file that contains a secret key using the DES algorithm. You should use
ObjectInputStream to read in the key. inputFile is the input to be decrypted and the
result is saved in the file outFile.
The program for decryption works like this:
java DecryptFile keyFile inputFile outFile
Again, keyFile contains a secret key using the DES algorithm. inputFile is the file to be
decrypted and the result is to be saved in outFile.
[7]
[End of Part II]
COMPS311(1315)
Page 12 of 15
Appendix A. Some useful Java APIs.
class javax.crypto.Cipher
public final byte[] doFinal()
throws IllegalBlockSizeException,
BadPaddingException
Finishes a multiple-part encryption or decryption operation, depending on how this cipher was
initialized.
public final byte[] doFinal(byte[] input)
throws IllegalBlockSizeException,BadPaddingException
Encrypts or decrypts data in a single-part operation, or finishes a multiple-part operation. The
data is encrypted or decrypted, depending on how this cipher was initialized.
public static final Cipher getInstance(String transformation)
throws NoSuchAlgorithmException,
NoSuchPaddingException
Generates a Cipher object that implements the specified transformation.
public final void init(int opmode,
Key key) throws InvalidKeyException
The cipher is initialized for one of the following four operations: encryption, decryption, key
wrapping or key unwrapping, depending on the value of opmode.
public final byte[] update(byte[] input,
int inputOffset,
int inputLen) throws IllegalStateException
Continues a multiple-part encryption or decryption operation (depending on how this cipher
was initialized), processing another data part.
interface java.sql.Connection
PreparedStatement prepareStatement(String sql) throws SQLException
Creates a PreparedStatement object for sending parameterized SQL statements to the
database.
class java.lang.Math
public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Returned values are chosen pseudorandomly with (approximately) uniform distribution from
that range.
interface java.sql.PreparedStatement
ResultSet exectueQuery() throws SQLException
Executes the SQL query in this PreparedStatement object and returns the ResultSet object
generated by the query.
void setString(int parameterIndex, String x) throws SQLException
Sets the designated parameter to the given Java String value. The driver converts this to an
SQL VARCHAR or LONGVARCHAR value (depending on the argument's size relative to the driver's
limits on VARCHAR values) when it sends it to the database.
public class java.rmi.server.UnicastRemoteObject
interface java.sql.ResultSet
double getDouble(int columnIndex) throws SQLException
Retrieves the value of the designated column in the current row of this ResultSet object as a
COMPS311(1315)
Page 13 of 15
double in the Java programming language.
String getString(int columnIndex) throws SQLException
Retrieves the value of the designated column in the current row of this ResultSet object as a
String in the Java programming language.
class java.security.Signature
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
Generates a Signature object that implements the specified digest algorithm. If the default
provider package provides an implementation of the requested digest algorithm, an instance of
Signature containing that implementation is returned. If the algorithm is not available in the
default package, other packages are searched.
public final void initSign(PrivateKey privateKey) throws InvalidKeyException
Initialize this object for signing. If this method is called again with a different argument, it
negates the effect of this call.
public final void initVerify(PubicKey publicKey) throws InvalidKeyException
Initializes this object for verification. If this method is called again with a different argument, it
negates the effect of this call.
public final byte[] sign() throws SignatureException
Returns the signature bytes of all the data updated. The format of the signature depends on the
underlying signature scheme.
public final void update(byte[] data) throws SignatureException
Updates the data to be signed or verified, using the specified array of bytes.
public final boolean verify(byte[] signature) throws SignatureException
Verifies the passed-in signature.
Appendix B JSP objects
request
public String getParameter(String name)
This is the method, used for getting the value of the HTML form attribute. This method returns
the string type value i.e. the value of the specified field of an HTML form.
COMPS311(1315)
Page 14 of 15
Appendix C XML Scheme
Elements
<xs:element name='xxx' type='yyy' minOccurs='zzz' maxOccurs='kkk'>
</xs:element>
<xs:sequence> </xs:sequence>
sequence of
components
complex
<xs:complexType> </xs:complexType>
type
elements
[End of Paper]
COMPS311(1315)
Page 15 of 15
Download