Appendix is attached at the end of the paper, which contains some useful Java and Android APIs.
Part I [60 marks]
You should attempt ALL questions in this part of the paper. This part carries 60% of the total examination marks. Ask for Answer Books if required and clearly identify yourself and your answer with the question number.
Question 1 [5 marks]
State whether each of the following statements is true or false:
(i) Thread is started by invoking the run() method.
(ii) A database connection can only be used in one query. Another database connection must be created for the next query.
(iii) JSP is a client-side script.
(iv) The secret key method can be used to protect the integrity of a message.
(v) Android application can only be developed by Java programming language.
[5]
Question 2
(a) State the output of executing this program.
[6 marks]
public class ExceptionTest {
public static void main(String[] args) {
try { System.out.println(10); if (true) {
throw new RuntimeException(); }
System.out.println(20);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(30); } catch (Exception e) {
System.out.println(40); }
System.out.println(50); }
}
[2]
(b) Complete the following code to convert the words to uppercase and collect the words that begin
with “A”.
[2]
(c) Describe what an Optional object is, and how it can be used as a safer alternative than a reference that may be null.
[2]
COMP S311 (xx15) Specimen Page 3 of 21
String[] words =
“Advanced Java Programming and Mobile Application Development” .split(” “);
List
Question 3 [7 marks]
Write a program CountIntegers that uses thread pool to count the total number of integers in text files within a directory. The program displays the total number of integers in each file and all files. Integers are delimited by whitespaces. A text file is a file with the .txt extension. Each text file is processed in a thread from the thread pool. The program should have two command- line parameters – the directory that contains text files, and the maximum number of threads in the thread pool.
For example, after executing the command:
> java CountIntegers filedir 5
May generate the output:
Note that the order of the output corresponding to the number of integers for each of the file depends on which thread finishes first. You are not required to implement input validation of command-line parameters or handling of I/O errors.
[7]
Question 4 [6 marks]
(a) Which methods of the Socket class do you use to open streams for reading data from and
file1.txt has 5 integers file3.txt has 3 integers file2.txt has 8 integers
Total number of integers are 16.
writing data to?
(b) State two advantages of using database system compared to file system.
(c) Suggest one scripting element for outputting an integer value in JSP.
Question 5
(a) Consider the enforcement of this security policy file in a program.
State whether each of the following operations is permitted.
(i) new File(“C:\\Windows\\”).list()
(ii) new File(“C:\\Windows\\file.txt”).exists()
(iii) new File(“C:\\Windows\\system32”).list()
(iv) new File(“C:\\Windows\\system32\\file.txt”).exists()
[2] [2] [2]
[6 marks]
grant {
permission java.io.FilePermission “C:${/}Windows${/}”, “read”; };
COMP S311 (xx15) Specimen
Page 4 of 21
(b) (i) What is the advantage of the secret key method over the public key method? (ii) What is the advantage of the public key method over the secret key method?
Question 6
(a) Given the distribution of Android devices in use:
(http://developer.android.com/resources/dashboard/platform-versions.html)
[4]
[8 marks]
[2]
Which version has the largest share of the distribution? If you wish to target for 95% or more of Android devices, which API level should you use and what is the corresponding distribution?
(b) State two core system services provided by Linux kernel in Android system.
(c) Describe the three important loops for controlling an activity lifecycle.
[3] [2] [3]
COMP S311 (xx15) Specimen
Page 5 of 21
Question 7 [10 marks]
(a) There are two ways in which the Handler class sends code to the UI thread for execution. What
are they?
[2]
(b) In the listing below, the “run()” method of the Runnable class “PostTask” is defined to accumulate the total from 1 to value of the integer variable “max”. After the evaluation completed, the TextView object “result” will be updated with the accumulated result.
public class MainActivity extends AppCompatActivity implements OnClickListener {
private Button button; private TextView result; private EditText input; private long max;
…
@Override
public void onClick(View v) {
result.setText(“Start compute…”);
max = Long.parseLong(input.getText().toString().trim()); Runnable task = new PostTask();
Thread thread = new Thread(task);
thread.start();
} …
private class PostTask implements Runnable { @Override
public void run() {
long total = sum(max);
String resultText = “The accumulated value from 1 to ” +
max + “is ” + total; result.setText(resultText);
} }
// Method for summing up from 1 to the value of parameter input public long sum(long input) {
// Add code for part
} }
(i) Complete the “sum” method which returns the sum from 1 to the value of parameter “input”. [2]
(ii) According to the rule of single thread model, UI component cannot be accessed outside from the UI thread. Modify the above program to solve this problem by using the “post(Runnable)” method of the “View” class.
[6]
COMP S311 (xx15) Specimen Page 6 of 21
Question 8 [4 marks] Given the following listing, suggest an approach to improve the performance. Modify the code
for illustration.
…
private class Ball {
…
void drawOn(Canvas canvas) {
Paint paint = new Paint(); paint.setColor(color); canvas.drawCircle(x, y, radius, paint);
} }
…
It is assumed that the “drawOn” method is invoked several times for each second. Question 9 [8 marks]
(a) What types of transformation are supported by view animation in Android?
(b) In no more than 200 words, describes and illustrates with diagram about what you would see
when the Android application program “MainActivity” is started. Listing below depicts the layout resource file “main.xml”
Listing below depicts the animation resource file “animation.xml”
[4]
[2]
COMP S311 (xx15) Specimen Page 7 of 21
Listing below depicts the activity class “MainActivity.java”
public class MainActivity extends AppCompatActivity {
TextView textView1; // Corresponding to TextView with id textView1
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); …
/* Performs animation on a TextView. */ Animation animation =
AnimationUtils.loadAnimation(this, R.anim.animation); textView1.startAnimation(animation);
} }
COMP S311 (xx15) Specimen
Page 8 of 21
[End of Part I]
[6]
Part II [40 marks]
Answer no more than FOUR (4) questions from this part of the paper. Each question is worth 10 marks. This part carries 40% of the total examination marks. Ask for Answer Books if required and clearly identify yourself and your answer with the question number.
Question 10 [10 marks]
Write a multithreaded Java TCP server. The communication between the client and server is described as follows.
– The server listens to requests at port 12345.
– When a client request arrives at the port, a new thread is created to serve it.
– Upon connection, the client sends to the server a string (in a line) that represents the
client’ s name.
– The client then sends a number of strings. The server checks whether the string matches
a connected client’s name; it returns a string of “yes” or “no” to reply whether there is
a match.
– The client finally disconnects 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 currently-connected clients. Either use a built-in thread-safe collection, or implement synchronization in your code. You need to add the client’s name to the data structure when a client connects, and remove the name when the client disconnects. You can assume that all users behave normally and do not need to handle exceptional cases.]
COMP S311 (xx15) Specimen
Page 9 of 21
[End of Question 10]
[10]
Question 11 [10 marks]
In this question, you develop a JSP that displays product information in a database table. The database table, called Products, has three columns.
– A Name column, of type CHAR(30), contains the name of a product.
– A Code column, of type CHAR(8), contains the product code.
– A Quantity column, of type INTEGER, contains the quantity of the product in stock.
Sample data of the table are shown below.
The JSP takes a parameter, called quantity, from the HTTP request. The parameter can be specified directly in the URL in the browser’s address bar like: http://localhost:8080/web/stock.jsp?quantity=20
or using an HTTP form like this:
Check product stock
The JSP displays all products whose quantity in stock is less than or equal to the quantity parameter. This screenshot shows the output when the quantity parameter is 20.
COMP S311 (xx15) Specimen Page 10 of 21
If the quantity parameter is not specified in the request, empty, or invalid (e.g. 55err), the JSP displays an error message.
A skeleton of the JSP is given below. It contains the database connection information and the SQL command. Complete the JSP.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*" %> <% String driver = "org.apache.derby.jdbc.ClientDriver"; Class.forName(driver); String dbUrl = "jdbc:derby://localhost:1527/COREJAVA;create=true"; String dbUsername = "dbuser"; String dbPassword = "secret"; %>
// Add code here
COMP S311 (xx15) Specimen
Page 11 of 21
[End of Question 11]
[10]
Question 12 [10 marks] Develop two programs that perform DES encryption and decryption, respectively.
The encryption program works like this:
> java DesEncrypt keyFile inputFile outputFile
The keyFile is a file that contains a secret key using the DES algorithm. You should read the key as a SecretKey object using an ObjectInputStream. The inputFile contains the input to be encrypted, and the result is saved in the outputFile.
The decryption program works like this:
> java DesDecrypt keyFile inputFile outputFile
Again, the keyFile contains a secret key using the DES algorithm. The inputFile contains
the file to be decrypted, and the result is saved in the outputFile.
[End of Question 12]
[10]
COMP S311 (xx15) Specimen
Page 12 of 21
Question 13 [10 marks] (a) Define an Android string resource with the ID author_name and content “Peter Au”. State
how to refer to the resource ID in Java code.
(b) In this question, you work on an Android app that rolls three dice. Listing below depicts the layout resource file “activity_main.xml”.
[2]
COMP S311 (xx15) Specimen Page 13 of 21
(i)
Illustrate with diagram about what you would see when the Android application that loads the layout file “activity_main.xml” is started.
(ii)
Listing below depicts part of the activity class “MainActivity.java”.
public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
// Add code here
} }
Add code to the onCreate() method for the following features:
(i) Load the layout file “activity_main”.
(ii) Find the views of the three dice and the button, and keep them in variables.
(iii) Set up the button to handle click events. The handler generates three random integers, from 1 to 6 inclusive, and displays them in the three dice views.
COMP S311 (xx15) Specimen
Page 14 of 21
[End of Question 13]
[8]
Question 14 [10 marks]
(a) Name and briefly describe the two forms of intents.
[3]
(b) The preference framework in Android provides a flexible and convenient mechanism for manipulating shared preferences.
Listing below depicts part of the string resource file “strings.xml”.
…
…
Listing below depicts the preference screen layout resource file “prefs.xml”.
COMP S311 (xx15) Specimen Page 15 of 21
Illustrates with diagrams about what you would see when the preference screen defined in the layout resource file “prefs.xml” is shown. Sketches with diagram if preference component such as CheckBoxPreference, EditTextPreference, ListPreference, or MultiSelectListPreference is declared and selected.
[4]
(c) Specify the interface or abstract classes that used in the preference framework for representing the shared preferences and showing a screen of preferences for interacting with the user. Name the element used in the XML resource file for declaring a preference screen.
[End of Question 14]
[End of Part II]
Please check that you have written your examination number and student number on the cover of each answer book used. Failure to do so will mean that your work cannot be identified.
COMP S311 (xx15) Specimen Page 16 of 21
[3]