Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
76 views

Section A: Structured Questions (80 Marks) INSTRUCTION: Answer ALL Questions in The Space Provided

The document contains a structured question section with 9 multiple part questions about object-oriented programming concepts like classes, objects, inheritance, interfaces, and abstract classes. Some of the key questions ask about the difference between procedural and object-oriented programming, the relationship between classes and objects, writing constructors and methods, and implementing inheritance and interfaces.

Uploaded by

Visnu Manimaran
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
76 views

Section A: Structured Questions (80 Marks) INSTRUCTION: Answer ALL Questions in The Space Provided

The document contains a structured question section with 9 multiple part questions about object-oriented programming concepts like classes, objects, inheritance, interfaces, and abstract classes. Some of the key questions ask about the difference between procedural and object-oriented programming, the relationship between classes and objects, writing constructors and methods, and implementing inheritance and interfaces.

Uploaded by

Visnu Manimaran
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 18

SECTION A: STRUCTURED QUESTIONS (80 MARKS)

INSTRUCTION: Answer ALL questions in the space provided.

1.

What is the difference between procedural and object-oriented


programming?
2.

(2 marks)

Answer:
Procedural programming tries to solve the problem by implementing
procedures (methods) to solve the main problem. [1 mark]
Object-oriented programming is a collection of objects that interact with
each other to solve the main problem. [1 mark]

1.

What is the relationship between classes and objects? Give ONE (1) example.
2.

(2 marks)
Answer:
An object is created from class. [1 mark]
For example, a class of Dog with a name attribute can have Spike (a dog
object) and Brufus (another dog object). [1 mark]

1.

What is a method? Do all objects of the same class have the same methods?
2.

(2 marks)
Answer:
Method is the action that an object can take, also called behaviour. [1 mark]
Yes, all objects of the same class have the same methods. [1 mark]

4. Java provides a number of predefined classes that programmers can use to build


sophisticated programs.

a.

State the package that provides the following classes and give ONE (1)
example of a method from each class.
b.
Predefined Classes Java Packages Methods
Scanner
String
Random
Math
 (4 marks)
Answer:  java.util     e.g: nextInt(), nextDouble()
      java.lang     e.g: charAt(), length()
      java.util     e.g: nextInt(), nextDouble()
      java.lang     e.g: pow(), sqrt()
                [½ mark for each ]

b) Write a Java statement to import ALL classes from one of the package.
(1 mark)
Answer: import java.util.*;

5. Based on the following scenario, answer ALL of the following questions:

a.

Write a no-argument constructor for this class.


b.

(2 marks)

public PressureCooker () {
}
     [1M for  public PressureCooker, 1M for bracket & curly braces]     

a.

Write a Java statement to create an object using the no-argument


constructor.
b.

(2 marks)
PressureCooker pc1 = new PressureCooker();
                 [1M]                 [1M]

a.
Write another constructor for this class by including ALL data/variables
stated.
b.

(7 marks)

public PressureCooker(String model, char size, String colour,   


double price) [2 ½ M]
{ [ ½ M]
 this.model = model; [1M]
 this.size = size; [1M]
 this.colour = colour; [1M]
 this. price = price; [1M]

a.

Write a Java statement to create an object using the constructor you wrote in
Question 5 (c).
b.

(3 marks)

PressureCooker pc2 = new PressureCooker(“HD2139”,‘L’,“brown”,309.00);


    [1M]   [1M]    [1M]

a.

There will be a static method in the PressureCooker class, named


calculatePrice. This method receives ONE (1) parameter: an int type
variable named quantity. The method returns price, which is of type
double. Write the header of this method.
b.

(3 marks)

  public static double calculatePrice(int quantity) [½ M for


each]

a.

Write a complete method call for the method you wrote in Question 5 (e).
b.

(1 mark)
  double totalPrice = PressureCooker.calculatePrice(3);
        [½ M]  [½ M]

6. Explain the ways in which inheritance promotes software reuse and saves time during
program development.
(3 marks)
Answer:
Software reuse lets us write less code when developing the new subclass and
avoid duplication of common functionality between several classes by
building a class inheritance hierarchy. [1.5 marks]
With inheritance, the developer can save time during program development
by basing new classes on existing proven and debugged high-quality
software. [1.5 marks]

package accessmodifier

public class ProtectedClass {


   protected void message1() {
        System.out.println("Hello World");
   }
}
7. The following codes define TWO (2) classes, ProtectedClass and AccessModifier.
ProtectedClass class has  only ONE (1) method: message1()and
AccessModifier class has  TWO (2) methods: message2()and the
main()method.

package accessmodifier;

public class AccessModifier {


   
   protected void message2() {
        System.out.println("Good Morning");
   }

   public static void main(String[] args) {


       AccessModifier obj = new AccessModifier();
       obj.message1();
   }
}
However the codes cannot be compiled because of an error. Explain the
reason for the error and modify the statement in the codes to correct the
error. (Note: Assume there is no error in the main()method and you are not
allowed to change the number of methods in each class)
(3 marks)

Answer:
Protected access modifier can only be accessible through
inheritance. [2 marks]

public class AccessModifier extends ProtectedClass


[1 mark]

8. Given the following class definitions:


public class A {
public String m()
{   return "A";   }  
}
public class B extends A {  
public String m()
{   return "B";   }  
}  
public class C extends B {  
public String m()
{   return "C";   }
}  
public class Test {  
public static void main(String[] args)
{  
A a1 = new A();
          A a2 = new B();
          A a3 = new C();
System.out.println( a1.m() + a2.m() + a3.m() );  
}
}

a) Draw a UML class diagram for A, B and C classes, showing the inheritance
relationship among them.
(3 marks)
Answer:
b) What will be the output if we run the main method of Test class?
(3 marks)
Answer: ABC   1 mark for each correct output, -1 for incorrect output

9. Given the interface and class definitions below.


interface Drawable {
//Draw method will display the name of the object.
void draw();
}

public abstract class Shape{


    private String color;
    public abstract double calculateArea();
    public abstract double calculatePerimeter();
    public void setColor(String Color) {...}
    public String getColor() {...}
}

public class Rectangle extends Shape implements Drawable{


    private int length;
    private int width;
……………
}

a) What are the methods that should be implemented in the Rectangle class?
(3 marks)
Answer:  
draw() , calculateArea(), calculatePerimeter()
1 mark for each correct method

b) Implement ALL of the methods stated in the previous question.


(6 marks)
Answer:  
[2 marks for each correct method]

public void draw ()


        { System.out.println("I am drawing Rectangle
"); }//any relevant answer

public double  calculateArea ()


        { return length * width; }

public double  calculatePerimeter ()


        { return (2 * (length + width)); }

10. What exception will be thrown when the following code fragment is executed?

int [] array = {1,2,3,4,5,6};


System.out.println("value = " +array[6]);
(2 marks)
Answer: ArrayIndexOutOfBoundsException

11. What will be the output of the program?


public class X
{   
   try {   
           System.out.print("A");  
           badMethod();  
           System.out.print("B");  
       }
       catch (RuntimeException ex)
       {
           System.out.print("C");
       }
       catch (Exception ex1)
       {
           System.out.print("D");
       }
       finally
       {
           System.out.print("F");
       }
       System.out.print("G");
   }
   public static void badMethod()
   {
       throw new RuntimeException();
   }
}

(4 marks)
Answer: ACFG  minus 1 for each wrong answer (letter)

12. Given the following incomplete fragment of code, fill in the blanks with TWO (2) if
statements. Each can throw an Exception object if the value of a variable named  m
is

less than 0 (for the first if statement)



greater than 100 (for the second if statement)


When the exception is caught either of the following message will be displayed.
(4 marks)

   
  

Answer:
           if (m < 0)
             throw new Exception (m + " is a negative value");
           if (m > 100)
             throw new Exception(m + " is too large");
[2 marks for each correct if statement]

13. Given the following program.


import javax.swing.*;
public class MyFrame
{
 public static void main(String[] args)
 {
   JFrame frame = new JFrame("MyFrame");
   frame.setSize(400, 300);
   frame.setVisible(true);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}

a) Why does this program must import javax.swing package?


Answer: Because this program need to use JFrame class.
(1 mark)

b) State the name of the container class used in this program.

Answer:JFrame
(1 mark)
c) What is the width and height of the frame?
Answer:Width = 400 height = 300
(1 mark)
d) What is the effect to the output of this program if the frame.setVisible(true)
statement is removed?
Answer:The frame will not be shown or will not be visible.
(1 mark)

14. The following incomplete program is supposed to write "Hello world" to a file
named "myFile.txt". Fill in the blanks to complete the code.

//import the package


import ____(a)______;

public class WriteFile {


   public static void main(String[] args) throws
______(b)______ {
       
       //set up file and stream
       File outFile = ______(c)_________;
       ______(d)______ = new FileWriter(outFile);
       ________________(e)______________________;
       
       //write "Hello world" to the stream
       ________________(f)___________________;
       
       outStream.close();
   }
}

      (6 marks)

Answers:
a.

java.io.*
b.
c.

IOException
d.
e.

new File("myFile.txt")
f.
g.

FileWriter outFileStream
h.
i.

PrintWriter outStream = new PrintWriter(outFileStream)


j.
k.

outStream.println("Hello world")
l.

15. Complete the code to read the "Hello world" string from the file in Question
14.

File inFile = new File("myFile.txt");


FileReader fileReader = new FileReader(inFile);
________________________(a)___________________;
       
String str;
str = _______(b)_______;
      (2 marks)

Answers:
a.

BufferedReader bufReader = new BufferedReader(fileReader)


[2M]
b.
c.

bufReader.readLine()[1M]
d.

16. A list is a popular data structure to store data in sequential order.


a) Give TWO (2) differences between ArrayList and LinkedList.
(4 marks)
Answer:
1. Implementation:  ArrayList is the resizable array implementation of list
interface, while LinkedList is the Doubly-linked list implementation of
the list interface.
2. Performance:  Performance of ArrayList and LinkedList depends on the
type of operation. For instance, insert() or add(Object) operation in
LinkedList is generally fast as compare to ArrayList.
3. Initial Capacity:  If the constructor is not overloaded, then ArrayList creates
an empty list of initial capacity 10, while LinkedList only constructs the
empty list without any initial capacity.
[Any two]
b) Show the contents of aList after the following operations are performed.
Assume the list is initially empty.

ArrayList<Integer> aList = new ArrayList<Integer>();


aList.add(1);
aList.add(2);
aList.add(3);
aList.remove(2);
aList.add(1,3);
aList.add(4);
aList.set(3,5);
 
(4 marks)
Answer:  
v=[1, 3, 2, 5]
SECTION B: PROGRAMMING QUESTION (20 MARKS)
INSTRUCTION: Answer ALL questions in the space provided.

1.

A local Satellite Television Company has assigned you to write a Graphical


User Interface (GUI) application that can calculate a customer’s monthly bill.
There are two types of customers: Residential (has only one service
connection) and Business (has one or more connections). Both customer
types can subscribe to any number of premium channels. The monthly billing
amount is the total of basic service fee plus the premium channels charge.
The rates for the two customer types are as follows:
2.

Basic Service Fee Premium Channels


Charge
Residential RM20.00 RM7.50 per channel

Business RM75.00 for the first 10 RM20.00 per channel for


connections; RM5.00 for each any number of
additional connection connections
The application uses two classes, CustomerBill and CompanyBillingUI, as shown

in the UML diagram below:


The application CompanyBillingUI creates a CustomerBill object for calculating
the bill amount, which requires FOUR (4) input data which are:   customer type,
customer account number, number of service connections and number of premium
channels subscribed. The calcResidentialCustomer() and
calcBusinessCustomer() methods calculate and return the bill amount for the
Residential and Business customers respectively. The toString() method returns
the bill information which is displayed in CompanyBillingUI.

The CompanyBillingUI class has the following actionPerformed method:


Method displayBTNActionPerformed() : to read the four inputs, create


the  CustomerBill object and get the billing information by calling the
toString()method of the CustomerBill object and display the billing
information in the output text area.  

The GUI, together with the names of its GUI components, are shown below:
Based on the provided information above, answer all of the following questions:
a.

Complete the definition of the CustomerBill class in the space provided in


the next page.
b.
        (12 marks)

public class CustomerBill {


   private String custType;
   private String acctNum;
   private int numOfConnections;
   private int numOfPremChannels;
// TODO: add constructor method code here:
   public CustomerBill(String custType, String acctNum,
           int numOfConnections, int numOfPremChannels) {
//1.5M
       this.custType = custType; //0.5M
       this.acctNum = acctNum; //0.5M
       this.numOfConnections = numOfConnections; //0.5M
       this.numOfPremChannels = numOfPremChannels; //0.5M
   }
// TODO: add calcResidentialCustomer() method code here:
   public double calcResidentialCustomer() {              //1M
       double charge = 0.0; //0.5M
       charge = 20.00 + 7.50 * numOfPremChannels; //1M
       return charge; //0.5M
   }

 
 
 
 
 
 
 
// TODO: add calcBusinessCustomer() method code here:
   public double calcBusinessCustomer() { //1M
       double charge = 0.0; //0.5M
       if (numOfConnections <= 10) { //0.5M
        charge = 75.00 + (20.00 * numOfPremChannels); //1M
       } else {                   //0.5M
        charge = 75.00 +(numOfConnections - 10)*5.00 +(20.00 *
numOfPremChannels); //1.5M
       }
       return charge; //0.5M
   }
public String toString() {
       String billInfo = "";
       double charge = 0.0;
       if (custType.equals("Residential")) {
        charge = calcResidentialCustomer();
        billInfo = "Account Number: " + acctNum + "\n"
            + "Number of premium channels =
"+numOfPremChannels+ "\n"
            + "Amount Due = RM"+charge;
       } else {
          charge = calcBusinessCustomer();
          billInfo = "Account Number: " + acctNum + "\n"
          + "Number of service connections =
"+numOfConnections+ "\n"
          + "Number of premium channels = "+numOfPremChannels+
"\n"
          + "Amount Due = RM"+charge;  
       }
       return billInfo;
   }
}

a.

Complete the following displayBTNActionPerformed() in the space


provided:
b.

        (8 marks)

private void
displayBTNActionPerformed(java.awt.event.ActionEvent evt) {

 
// TODO: add your code here:    

 
String acctNum = acctNumTF.getText();  //0.5M
int numOfPremChannels = Integer.parseInt(numPremTF.getText());
//1M
int numOfConnections = 1; //0.5M
String custType = "Residential";         //0.5M
if (businessRB.isSelected()) {           //1M
   custType = "Business";              //0.5M
  numOfConnections = Integer.parseInt(numConnTF.getText());
//1M
}
CustomerBill bill =
      new CustomerBill(custType, acctNum, numOfConnections,
numOfPremChannels);                                    //2M
       outputTA.setText(bill.toString());              //1M
}

END OF QUESTIONS

You might also like