0% found this document useful (0 votes)
44 views

Solution Exam Questions Set 2 CSC2106 Object-Oriented Design & Programming

marking guide Exam questions CSC2106 Object-Oriented Design & Programming at Catholic University Of Cameroon Bamenda

Uploaded by

Djamen
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views

Solution Exam Questions Set 2 CSC2106 Object-Oriented Design & Programming

marking guide Exam questions CSC2106 Object-Oriented Design & Programming at Catholic University Of Cameroon Bamenda

Uploaded by

Djamen
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

CATHOLIC UNIVERSITY OF CAMEROON (CATUC), BAMENDA

P.O. Box 782 Bamenda, Cameroon

FIRST SEMESTER EXAMINATION 2023/2024 SESSION

FACULTY OF SCIENCE DEPARTMENT: Computer Science


LECTURER: DJAMEN NYONKEU Gildas
COURSE TITLE: Object-Oriented Design & Programming
COURSE CODE : CSC2106 CREDIT VALUE: 6 DURATION : 3h

INSTRUCTIONS: Answer all questions

Marking guide
Section A General Knowledge (12 pts)
1. Describe the following characteristics concerning JAVA: Dynamic, robust, object
oriented.
2. What is a Class? Object?
3. Which class allows to create a windows in JAVA?
4. Enumerate the various types of layouts which can be created in JAVA
5. What is the role of new operator?
6. What is the difference between the classic Array and ArrayList in JAVA?
7. Which class allows to display a Table frame in Java?
8. To create a table frame, you need to implement a table model from an abstract class, give
the name of the abstract class and one method of such class.
Section B (14 pts)
1. (3 pts) Write Text‐Based Application using Object‐Oriented Approach to display your
name.
// filename: Name.java
// Class containing display() method, notice the class doesnt have a main() method
public class Name {
public void display() {
System.out.println("Mohamed Faisal");
}
}
// filename: DisplayName.java
// place in same folder as the Name.java file
// Class containing the main() method
public class DisplayName {
public static void main(String[] args) {
Name myname = new Name(); // creating a new object of Name class
myname.display(); // executing the display() method in the Name class
}
}
2. (5 pts) What are the values of the following variables?
(a) double var1 = 10 / 3;
(b) int var2 = (int) (2.5 * 2.6);
(c) boolean var3 = !(3 > 3);
(d) boolean var4 = (121 % 11 == 0) || (5 == 5);
(e)int var5 = 11 % 3;
Answer
(a) 3.0 double var1 = 10 / 3;
(b) 6 int var2 = (int) (2.5 * 2.6);
(c) true boolean var3 = !(3 > 3);
(d) true boolean var4 = (121 % 11 == 0) || (5 == 5);
(e) 2 int var5 = 11 % 3;
3. (3 points) Declare a variable to hold the amount of money in your bank account and
initialize it to
245.25. Name your Java variable in a meaningful way so that any programmer would know
what
value it holds. Your variable name should be at least two words.

Answer: double accountBalance = 245.25;


4. (3 points) Give the return type and value of the following method calls on str (defined in
the above question).
(a) str.length()
(b) str.equalsIgnoreCase("HOW ARE YOU")
(c) str.indexOf("ou")
(d) str.lastIndexOf(" ")
(e) str.charAt(6)
(f) str.substring(1, 6)

answer
(a) str.length()
return type: int , value: 12
(b) str.equalsIgnoreCase("HOW ARE YOU")
return type: boolean , value: false
(c) str.indexOf("ou")
return type: int , value: 9
(d) str.lastIndexOf(" ")
return type: int , value: 7
(e) str.charAt(6)
return type: char , value: ‘e’
(f) str.substring(1, 6)
return type: String , value: “ow ar”

Section A General Knowledge (12 pts)


1. Describe the following characteristics concerning JAVA: Dynamic, robust, object oriented.
- Dynamic: This allows for flexibility in coding. The Byte code, which is a source code that is written in
one platform and can be executed in any platform.
- Robust: Java emphasizes strong error checking and robustness. It provides built-in exception
handling mechanisms and guarantees strong memory management.
- Object-oriented: Java is an object-oriented programming language, which means it encapsulates
data and methods within objects and supports principles like inheritance, polymorphism, and
encapsulation.

2. What is a Class? Object?


- Class: In Java, a class is a blueprint or template that defines the properties and behaviors (methods)
of objects. It provides a structure for creating objects of that particular class.
- Object: An object is an instance of a class. It represents a specific entity or instance of the class, with
its own unique set of data (attributes) and behaviors (methods).

3. Which class allows to create a windows in JAVA?


- The `javax.swing.JFrame` class allows creating windows (frames) in Java. It provides APIs for
creating and managing windows with features like title bars, buttons, panels, and components.

4. Enumerate the various types of layouts which can be created in JAVA


Some of the layouts that can be created in Java are:
- FlowLayout: Components are arranged in a single row, and if the container width is exceeded, they
wrap to a new line.
- BorderLayout: Components are arranged in five areas: North, South, East, West, and Center.
- GridLayout: Components are arranged in a grid with specified rows and columns.
- GridBagLayout: A flexible layout manager that arranges components based on constraints defined
for each component.
- BoxLayout: Components are arranged either horizontally or vertically in a single line.

5. What is the role of new operator?


- In Java, the `new` operator is used to create a new instance (object) of a class. It dynamically
allocates memory for the object and initializes its attributes and methods. In other words, it
instantiates a class to create an object that can be used in the programming

6. What is the difference between the classic Array and ArrayList in JAVA?
- Classic Array is a fixed-size data structure (the array size must always be mentioned) that stores
elements of the same type, while ArrayList is a dynamic-size data structure (that is, not a fixed sized
data structure) that can grow or shrink as needed.
- Classic Arrays can store both primitive types and objects, whereas ArrayList can only store objects.
- Classic Arrays use square brackets for declaration and have a fixed length, while ArrayList uses the
ArrayList class and can be resized.

7. Which class allows to display a Table frame in Java?


- The class that allows displaying a Table frame in Java is the `JTable` class from the Swing library.

8. To create a table frame, you need to implement a table model from an abstract class, give the name of the
abstract class and one method of such class.
The abstract class used for implementing a table model in Java is `AbstractTableModel`. One
method of this class is `getValueAt(int row, int column)`, which is used to retrieve the value at a
specific row and column in the table. This method needs to be overridden when implementing the
table model to provide the appropriate data for display in the table.
Section B (14 pts)
1. (3 pts) Write Text‐Based Application using Object‐Oriented Approach to display your
name.
// filename: Name.java
// Class containing display() method, notice the class doesnt have a main() method
public class Name {
public void display() {
System.out.println("Mohamed Faisal");
}
}
// filename: DisplayName.java
// place in same folder as the Name.java file
// Class containing the main() method
public class DisplayName {
public static void main(String[] args) {
Name myname = new Name(); // creating a new object of Name class
myname.display(); // executing the display() method in the Name class
}
}
2. (5 pts) What are the values of the following variables?
(a) double var1 = 10 / 3;
(b) int var2 = (int) (2.5 * 2.6);
(c) boolean var3 = !(3 > 3);
(d) boolean var4 = (121 % 11 == 0) || (5 == 5);
(e)int var5 = 11 % 3;
Answer
(a) 3.0 double var1 = 10 / 3;
(b) 6 int var2 = (int) (2.5 * 2.6);
(c) true boolean var3 = !(3 > 3);
(d) true boolean var4 = (121 % 11 == 0) || (5 == 5);
(e) 2 int var5 = 11 % 3;
3. (3 points) Declare a variable to hold the amount of money in your bank account and
initialize it to
245.25. Name your Java variable in a meaningful way so that any programmer would know
what
value it holds. Your variable name should be at least two words.

Answer: double accountBalance = 245.25;


4. (3 points) Give the return type and value of the following method calls on str (defined in
the above question).
(a) str.length()
(b) str.equalsIgnoreCase("HOW ARE YOU")
(c) str.indexOf("ou")
(d) str.lastIndexOf(" ")
(e) str.charAt(6)
(f) str.substring(1, 6)

answer
(a) str.length()
return type: int , value: 12
(b) str.equalsIgnoreCase("HOW ARE YOU")
return type: boolean , value: false
(c) str.indexOf("ou")
return type: int , value: 9
(d) str.lastIndexOf(" ")
return type: int , value: 7
(e) str.charAt(6)
return type: char , value: ‘e’
(f) str.substring(1, 6)
return type: String , value: “ow ar”

Section C ( 8 pts):
1) Explain characteristics of Object-Oriented Programming.
2) Write a program to find average of all the numbers stored in an array.
3) What is ‘this’ and what are different uses of it? Explain with example.
4) Compare and contrast abstract class and interface.
Answers:
1) Characteristics of Object Oriented Programming include: Encapsulation, Inheritance,
Polymorphism, Abstraction.
- Encapsulation: The bundling of data and methods into a single unit (class) to hide
implementation details.
- Inheritance: The ability of a class to inherit properties and behaviors from another class,
promoting code reuse.
- Polymorphism: The ability to use a single interface to represent different types of objects,
enabling code flexibility.
- Abstraction: The process of simplifying complex systems by breaking them down into
manageable and reusable components.
2) Java program to find the average of numbers in a given array:
java
public class AverageCalculator {
public static void main(String[] args) {
int[] numbers = { 5, 10, 15, 20, 25 };
int sum = 0;

for (int number : numbers) {


sum += number;
}
double average = (double) sum / numbers.length;
System.out.println("Average: " + average);
}
}

3) The keyword 'this' in Java refers to the current object within a method or constructor. It is
used to differentiate between instance variables and local variables when they have the same
names. Here are some different uses of 'this':
- To refer to instance variables: 'this' can be used to access or modify instance variables
within a class. For example:
java
public class Person {
private String name;
public void setName(String name) {
this.name = name;
}
}

- To invoke constructors: 'this' can be used to call one constructor from another constructor
within the same class. This is useful for constructor chaining. For example:
java
public class Rectangle {
private int width;
private int height;

public Rectangle() {
this(0, 0); // Calling another constructor with 'this'
}
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
}
- To pass the current object as an argument: 'this' can be used to pass the current object as
an argument to other methods or constructors. For example:
java
public class Circle {
private double radius;

public Circle() {
this(1.0); // Passing 'this' as an argument
}
public Circle(double radius) {
this.radius = radius;
}
public void printInfo() {
System.out.println("Radius: " + this.radius);
}
}

4) Abstract class vs. Interface:


- Abstract class: It can have both abstract and non-abstract methods. It cannot be
instantiated directly and serves as a base class for other classes. It can have instance
variables. Subclasses extend and implement the abstract class using the 'extends' keyword.
- Interface: It can only have abstract methods (no method implementations). It can be
implemented by multiple classes. It does not contain instance variables. Classes implement
interfaces using the 'implements' keyword.

5) The wrapper class in Java is used to convert primitive data types into objects. It provides
a way to treat primitive types as objects. Examples of wrapper classes in Java include
Integer, Double, Boolean, etc. These classes provide methods to perform various operations
on the wrapped primitive values, such as converting strings to numbers or comparing values.

Section D: GUI- in JAVA (7 pts )


Write a Swing application called SwingAdder as shown. The "ADD" button adds the two integers and display the
result. The "CLEAR" button shall clear all the text fields.

Hints: Set the content-pane to 4x2 GridLayout. The components are added from left-to-right, top-to-bottom.

import java.awt.*; // Using AWT's layouts


import java.awt.event.*; // Using AWT's event classes and listener interfaces
import javax.swing.*; // Using Swing's components and container

// A Swing application extends from javax.swing.JFrame


public class SwingAdder extends JFrame {
private JTextField tfNumber1, tfNumber2, tfResult;
private JButton btnAdd, btnClear;
private int number1, number2, result;

// Constructor to set up UI components and event handlers


public SwingAdder() {
// Swing components should be added to the content-pane of the JFrame.
Container cp = getContentPane();
// Set this Container to grid layout of 4 rows and 2 columns
cp.setLayout(new GridLayout(4, 2, 10, 3));

// Components are added from left-to-right, top-to-bottom


cp.add(new JLabel("First Number ")); // at (1, 1)
tfNumber1 = new JTextField(10);
tfNumber1.setHorizontalAlignment(JTextField.RIGHT);
cp.add(tfNumber1); // at (1, 2)
.......
.......

btnAdd = new JButton("ADD");


cp.add(btnAdd); // at (4, 1)
btnAdd.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
number1 = Integer.parseInt(tfNumber1.getText());
......
}
});

btnClear = new JButton("CLEAR");


cp.add(btnClear); // at (4, 2)
btnClear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent evt) {
......
}
});

setDefaultCloseOperation(EXIT_ON_CLOSE); // for the "window-close" button


setTitle("Swing Adder");
setSize(300, 170);
setVisible(true);
}

// The entry main() method


public static void main(String[] args) {
// For thread safety, use the event-dispatching thread to construct UI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SwingAdder(); // Let the constructor does the job
}
});
}
}

Section E: (6 pts)
import java.io.*;
public class Employee {

// salary variable is a private static variable


private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
int S = 0;
public static void main(String args[]) {
salary = 1000;
for (int i= 0; i<10 ; i= i+2) {
S += i;
}
System.out.println(DEPARTMENT + "average salary:" + salary);
}

1. What are the values of S and i at the end of the loop?


2. What are the meanings of the keywords private, public and static used in this code?
3. What are the attributes and methods of this JAVA class?
4. Declare the default constructor for this class.

Section E 6 pts
import java.io.*;
public class Employee {

// salary variable is a private static variable


private static double salary;

// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
int S = 0;
public static void main(String args[]) {
salary = 1000;
for (int i= 0; i<10 ; i= i+2) {
S += i;
}
System.out.println(DEPARTMENT + "average salary:" + salary);
}

1. What are the values of S and i at the end of the loop?


At the end of the loop, the value of "S" will be 20, and the value of "i" will be 10.
2. What are the meanings of the keywords private, public and static used in this code?
- "private" is an access modifier that restricts access to the variable "salary" within the class itself.
- "public" is an access modifier that allows unrestricted access to the methods and variables from
anywhere.
- "static" is a keyword that makes the variable "salary" shared among all instances of the class. It
can be accessed without creating an object of the class.
3. What are the attributes and methods of this JAVA class?
The attributes of the "Employee" class are:
- "salary" (private static double): a variable to hold the salary.
- "DEPARTMENT" (public static final String): a constant representing the department.
- "S" (int): an instance variable to accumulate the sum of even numbers in the loop.
The methods in the class are:
- "main" (public static void): the entry point of the program where the salary is set and the loop is
executed

4. Declare the default constructor for this class.


public Employee() {
// Constructor code goes here
}

Section F: (13 marks)


Consider the following class hierarchy where Class Car is the supper class and the classes ClassicCar and
SportCar are two subclasses derived from Car.
Class CarExhibition contains a filed of type ArrayList that stores objects of type Car.

(a) Class Car is an abstract class. Explain the role of an abstract class. [1 marks]
(b) Write a Java version of class Car assuming it has this constructor:
public Car(double price, int year)
and that the method calculateSalePrice ( ) is abstract. [3 marks]
(c) Write a Java version of class ClassicCar assuming it has this constructor:
public ClassicCar (double price, int year) [2 marks]
and that the method calculateSalePrice ( ) returns 10,000 as the sale price of the car.

d) Write a Java version of class SportCar assuming it has this constructor:


public SportCar(double price, int year) [3 marks]

and that the method calculateSalePrice ( ) calculates the sale price of the car as follow:
if year > 2000 then the sale price is 0.75 * its original price; if year > 1995 then the sale price
is 0.5 * its original price; otherwise the sale price is 0.25 * its original price
e) Write a Java version of class CarExhibition assuming it has this constructor:
public CarExhibition( ) [4 marks]
where CarExhibition has cars of different types stored in an arraylist and getTotalPrice method that
returns the total prices of all cars in the exhibition.

The outline solution is as follows:


(a)An abstract class provides sort of generalization. It can be reused for different concrete
classes where, each concrete class that inherits from an abstract class can implement any
abstract method in it.
1 mark
(b) Car Class Definition
abstract public class Car
{ protected double price;
protected int year;
public Car(double price, int year)
{ this.price = price; this.year = year; }
public String toString()
1 mark
1 mark
ClassicCar
double calculateSalePrice( )
Car
price: double
year: int
String toString( )
double calculateSalePrice ( )
SportCar
double calculateSalePrice ( )
CarExhibition
void addCar (double price, int year)
void addSportCar (double price, int year)
int getTotalPrice( )
Marking Scheme Final Exam Object-Oriented Paradigms (Section 3) February 5, 2007 6
{ return ("Price = "+price+" Year = "+year); }
public abstract double calculateSalePrice ( ); //abstract method
}
0.5 mark
0.5 mark
(c) ClassicCar Definition
public class ClassicCar extends Car
{ public ClassicCar(double price, int year)
{ super (price, year); }
public double calculateSalePrice ( )
{ return 10000; }
}
0.5 mark
0.5 mark
1 mark
(d) SportCar Class Definition
public class SportCar extends Car
{ public SportCar(double price, int year)
{ super (price, year); }
public double calculateSalePrice ( )
{ double salePrice;
if (year > 2000)
salePrice = 0.75 * price;
else if (year > 1995)
salePrice = 0.5 * price;
else
salePrice = 0.25 * price;
return salePrice;
}
}

0.5 mark
0.5 mark
2 mark
(e) CarExhibition Class Definition
import java.util.ArrayList;
import java.util.Iterator;
public class CarExhibition
{ private ArrayList cars;
public CarExhibition()
{ cars = new ArrayList(); }

public void addCar (double price, int year)


{ Car cr = new ClassicCar(price, year); //Superclass/subclass relationship
cars.add(cr);
}
public void addSportCar (double price, int year)
{ cars.add(new SportCar(price, year)); }

public double getTotalPrice()


{ double result = 0;
Iterator it = cars.iterator();
while (it.hasNext())
{ Car cr = (Car) it.next();
result = result + cr.calculateSalePrice();
}
return result;
}
}

You might also like