Northumbria University Programming 2 (KV4001) Exam: Detailed Solutions

Verified

Added on  2022/11/26

|17
|3422
|494
Homework Assignment
AI Summary
This document contains comprehensive solutions for a Programming 2 exam. The exam covers a range of core programming concepts including testing methodologies (White Box and Black Box testing, Equivalence Partitioning, Boundary Value Analysis), inheritance (abstract classes, interfaces, class hierarchies), exception handling (checked and unchecked exceptions, try-catch blocks), and file handling (File class, Scanner). The solutions provide detailed code examples and explanations for each question, addressing topics like statement coverage, branch coverage, multiple condition coverage, similarities and differences between abstract classes and interfaces, creating subclasses, handling input mismatches, and file operations. This resource is designed to assist students in understanding and mastering these fundamental programming concepts.
Document Page
EXAMINATION PAPER
Module Title: Programming 2
Module Code: KV4001
Module Tutor: XXXX
Examination set by: XXXX
Academic Year: XXXX
Month: XXXX
Time Allowed: 3 Hours
INSTRUCTIONS TO CANDIDATES
Please read carefully before you begin your examination.
This is an open notes exam.
You are allowed to use up to 6 sides (3 sheets) of handwritten A4 notes to help
you during the examination. Word-processed material will be removed by the
invigilators! Each page should have your Northumbria ID at the top of the page
& clearly show page ‘x’ of ‘y’ pages. No other material (books, other loose
paper, etc.) is allowed. These must be handed in with your exam paper and
answer booklet(s) at the end of your exam.
No additional materials are allowed.
There is one section in this exam paper.
There are four questions on this exam paper .
Answer three questions ONLY. If you answer four questions only the first three
will be marked.
Marks for each question part are indicated after each part.
Total marks per question are shown below each question.
This examination is marked out of 60 marks.
It is worth 70 % of the total marks for this module.
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
PLEASE NOTE: You should only answer the number of questions required
above. If you answer more than this, your answers will be marked in the order
they appear in your answer sheets, up to and including the required number.
Any additional answers will not be marked. Please cross out any work that you
do not wish the marker to consider. Please check your work to ensure you
have answered the correct number of questions and they are clearly
numbered.
You must abide by the University’s regulations on academic misconduct.
Formal enquiry proceedings will be instigated if there is any suspicion of
misconduct in your work.
1. Testing
(a
)
The following are possible White Box “criteria” that may be used to
guide the selection test cases:
For each criteria give a brief definition and discuss its relative
strengths and weaknesses. You must illustrate your answer with
short sections of Java code
Statement Coverage;
Statement coverage is said to ensure that each statement in
the code is executed at-least once.
Advantage:
1) It is used to measure the code quality
2) It tests whether the code performs the task correctly
Disadvantage:
1) False condition is not tested
2) Does not understand logical operator functions
3) It does not test whether loop terminates or not
Code:
public class Test{
public static void main(String args[]){
System.out.println(“Numbers”);
int n= 10;
if(n%2==0){
for(int i=0;i<5;i++){
System.out.println(i);
}
}
else{
for(int i=5;i<10;i++){
System.out.println(i);
}
}
}
}
Description:
(8 Marks)
Document Page
Statement coverage does not test the else part of code and does
not check termination condition in for loop inside the if condition.
Branch Coverage;
Branch coverage is said to ensure that all possible branch i.e.
all code statements in both true and false branches of decisions will
be tested at-least once
Advantages:
1) It checks whether the code statement in all branches are
executed
2) It ensures that no branch leads to abnormal behaviour of
program execution.
Disadvantages:
1) It tests the condition in the branch statement in short circuit
manner. It ignores the branches in Boolean expression.
Code:
public class Test{
public static void main(String args[]){
System.out.println(“Numbers”);
int n1= 10;
int n2= 20;
if((n1%2==0) || (n2%3==0)){
for(int i=0;i<5;i++){
System.out.println(i);
}
}
else{
for(int i=5;i<10;i++){
System.out.println(i);
}
}
}
}
Description:
Branch coverage test both if and else part of code and checks for
termination condition in for loops. In branch condition only n1%2==0
is executed other condition n2%3==0 is not executed.
Multiple Condition Coverage.
In Multiple Condition coverage, a decision with multiple
condition is tested such that all possible of combination of condition
is tested.
Advantages:
1) It tests all possible combination of Boolean expression
Disadvantages:
1) It is difficult to determine the minimum set of test cases
required for a very complex Boolean condition expression.
Code:
Document Page
public class Test{
public static void main(String args[]){
System.out.println(“Numbers”);
int n1= 10;
int n2= 20;
if((n1%2==0) || (n2%3==0)){
for(int i=0;i<5;i++){
System.out.println(i);
}
}
else{
for(int i=5;i<10;i++){
System.out.println(i);
}
}
}
}
Description:
Multiple condition coverage forms a truth table to test all possible
condition of boolean expression((n1%2==0) || (n2%3==0)). It tests all
possible combination.
(b
)
A Black Box approach to generating test cases is based on
“Equivalence Partitioning”
(i) Explain what we mean by Equivalence Partitioning. (2 Marks)
Solution:
Equivalence partitioning is a software testing technique which
divides input data into partitions such that at-least one test cases can
be derived from each partition.
(ii) Define the equivalence classes for each of the following:
An integer in the range 1 to 100
Solution:
Valid Equivalence Classes: [1-100]
Invalid Equivalence Classes: [greater than 100]
Invalid Equivalence Classes: [less than 1]
An input consisting of between 2 and 4 names
Solution:
2D Shapes = {Square, Rectangle, Cirlce} (4 marks)
Valid Equivalence Classes: [Square]
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
Valid Equivalence Classes: [Rectangle]
Valid Equivalence Classes: [Circle]
Invalid Equivalence Classes: [Cube]
(c) A program reads three integer values. The values are interpreted as
representing the lengths of the sides of a triangle. The program
prints a message that states whether the triangle is scalene,
isosceles or equilateral.
By considering the input to the programme develop a set of test
cases using Boundary Value Analysis to construct a set of test cases
for the program. You must clearly show how you derived the test
cases (6 marks)
Solution:
Test ID
Side A Side B Side C Expected Result
1 10 10 10 Equilateral Triangle
2 20 10 10 Isosceles Triangle
3 10 20 10 Isosceles Triangle
4 10 10 20 Isosceles Triangle
5 10 20 30 Scalene Triangle
Document Page
2. Inheritance
(a
) What are the similarities/difference between an Abstract class and
Interface?
(6
marks
)
Solution:
Similarities:
Both Abstract class and interfaces cannot be instantiated
Both abstract class and interface contains abstract methods
Differences:
Abstract Class
Interface
It can contain both final and
non-final variables Interface can contain only final
variables
Does not support multiple
inheritance Supports multiple inheritance
Abstract class can contain
constructors Interface cannot contain
constructors
Abstract class can inherit both
interface and classes An interface can inherit only
from another interface
Give a brief example of a Java Abstract class containing an abstract
method, clearly labelling those parts of the code that relate to the abstract
class
(2
marks
)
Solution:
// class is preceded by keyword abstract
public abstract class Shape
// data member of abstract class
private String color;
// constructor of abstract class
public Shape(String color){
this.color=color;
}
// normal methods of abstract class
public String getColor(){
return color;
}
// abstract methods of the class
public abstract double area();
public abstract double perimeter();
}
Give a brief example of a Java Interface, clearly labelling those parts of the
code that relate to the interface
(2
marks
)
Solution:
Document Page
// interface named is preceded by keyword interface
public interface Shape
// data member of interface are default public and final
double PI=3.14;
// member function of interface are default public and abstract
double area();
double perimeter();
}
(b
)
A class called People holds a list of references in an ArrayList. References
may be either of type Student or Lecturer. The data needed for each type
of item is specified in the following table:
You may assume that each field is a String.
(i)Write sections of code for a superclass called Person and two
subclasses called Lecturer and Student, showing the class
declarations, the attribute declarations and the constructors.
(6
marks
)
Solution:
class Person {
private String fName;
private String lName;
private String gender;
public Person(String fName, String lName, String gender) {
this.fName=fName;
this.lName=lName;
this.gender=gender;
}
}
class Lecturer extends Person {
private String roomNo;
private String grade;
private String dept;
public Lecturer(String fName, String lName, String gender,String
roomNo, String grade, String dept) {
super(fName,lName,gender);
this.roomNo=roomNo;
this.grade=grade;
this.dept=dept;
}
}
fName lName gender roomNo grade dept id course
Lecturer x x x x x x
Student x x x x x
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
class Student extends Person {
private String id;
private String course;
public Student(String fName, String lName, String gender,String id,
String course) {
super(fName,lName,gender);
this.id=id;
this.course=course;
}
}
(ii)Write a toString() method for the class Lecturer assuming Person has a
toString() method which returns a string in the format:
fName, lName, gender
(2
marks
)
Solution:
class Lecturer extends Person {
private String roomNo;
private String grade;
private String dept;
public Lecturer(String fName, String lName, String gender,String
roomNo, String grade, String dept) {
super(fName,lName,gender);
this.roomNo=roomNo;
this.grade=grade;
this.dept=dept;
}
@Override
public String toString() {
return super.toString()+", "+roomNo+", "+grade+", "+dept;
}
}
(iii)Write a method for class People to output all the Lecturer objects held
in the ArrayList.
(2
marks
)
Solution:
public class People{
private ArrayList<Person> personList;
public People() {
personList=new ArrayList<Person>();
}
Document Page
public People(ArrayList<Person> personList) {
this.personList=personList;
}
public void displayLecturers() {
for(Person person:personList) {
if(person.getClass().getSimpleName().equals("Lecturer")){
System.out.println(person);
}
}
}
Document Page
3. Exceptions and Files
(a) Briefly answer each of the following questions
(i) What is a Java Exception?
(2
marks)
Solution:
Exception is the error that occurs during the execution of program.
Exception when occurred, disrupts the normal execution of the user
program and the application abnormally terminates.
For example:
In division operation, if the divisor is zero, java raises an
Arithmetic exception for Divide by zero
(ii)Give two different ways to generate an Exception
(2
marks)
Solution:
An exception can be raised in java by the following ways
i) Executing the statement that raises the exception E.g. raise
index out of bound exception by executing the statement that
that access the array outside its bound.
ii) Explicitly throw an exception from a method using throw key
word. E.g. throw new NullPointerException("My Exception");
(iii)What are Checked Exceptions and Unchecked Exceptions?
(2
marks)
Solution:
Checked Exception:
Checked exception are checked at compile time. If some statement
has the possibility of raising checked exception, then the program
raises a compile time error if such exception handling code is not
written nor it specifies the exception in throws list.
Example:
If the program uses the FileReader() then Java program checks for
FileNotFoundException is handled in the program. This is done
because the FileReader() throws checked exception named
FileNotFoundException
Unchecked Exception:
Unchecked exception is not checked at compile time. If some
statement has the possibility of raising unchecked exception the
compiler does not raise error and neither force to handle such
exception nor request them to specify in throws list.
Example:
tabler-icon-diamond-filled.svg

Paraphrase This Document

Need a fresh take? Get an instant paraphrase of this document with our AI Paraphraser
Document Page
The division operation is prone to ArithmeticException but the
program does not requires the user to handle it even though it
performs division operation.
(b) Consider the following Java code section:
int myInt ;
myInt = keyboard.nextInt();
If a user enters a non-Int value via the keyboard an
InputMismatchException error occurs. Show how you would handle
this using Java’s Exception handling facilities.
(4
marks)
Solution:
int myInt=0 ;
boolean valid=false;
while(!valid) {
try {
myInt = keyboard.nextInt();
valid=true;
}
catch(InputMismatchException ex) {
System.out.println("Invalid Data");
keyboard.nextLine();
}
}
(c) (i) What is the purpose of the File class?
(2
marks)
Solution:
Java File Class is used to represent the directory paths and files in
abstract way. Java File class is used to test existence of file, create
new file, delete file, rename file etc.
(ii)Does constructing a File object automatically create a disk file?
(1
mark)
Solution:
Constructing a File object does not automatically create a disk file.
The file object acts as an interface to file or directory which may or
may not exist in the disk.
(iii)A program uses a Scanner constructor with the parameter new
File( “thisFile.txt”). What happens if thisFile.txt does not exist?
Solution:
The Scanner constructor with the parameter new File( “thisFile.txt”)
raises checked exception FileNotFoundException if the input file
thisFile.txt does not exist
(1
mark)
Document Page
(d) The code in Figure 3.1 shows a partially complete class for writing
to a text (.txt file). Write the code needed to complete each of the
three methods. Where appropriate your code should deal with
exception conditions.
Figure 3.1 is on the next page.
Solution:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class WriteToFile {
private File file;
private PrintWriter output;
public WriteToFile(String fileName)
{
file=new File(fileName);
}
public void makeLink() throws FileNotFoundException
{
chevron_up_icon
1 out of 17
circle_padding
hide_on_mobile
zoom_out_icon
[object Object]