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

Solutions Exam Questions Set 1 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)
97 views

Solutions Exam Questions Set 1 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/ 13

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 (10 pts)
(Very Short Answer Questions)
1) (i) How does JAVA achieve platform independence?
(ii) What are the commands used to compile and run the JAVA Programs.
(iii) Determine the value of each of the following logical expressions if a = 5, b = 10 and c =
–6
a) a>b && a<c
b) a<b && a>c
c) a==c|| b>a
d) b>15 && c<0 || a>0
(iv) Explain any three string functions used in JAVA.
(v) Explain the difference between do-while statement and while statement.
(vi) Define an abstract class.
(vii) What is the Java virtual machine (JVM)?

Answers:
1) (i) - Platform independence is achieved in JAVA through bytecode compilation and the
use of the Java Virtual Machine (JVM).

(iii) - Command to compile: javac,


- Command to run: java

(iv) - a) false, b) true, c) true, d) true

(v) - Examples of string functions: length(), substring(), toLowerCase()


- length(): This function returns the length of a string.
- substring(): It extracts a portion of a string based on the specified indexes.
- toLowerCase(): This function converts the string to lowercase.
(vi) - Difference: do-while executes the loop body at least once, while checks the condition
first and executes the loop body if true.

(vii) - An abstract class is a class that cannot be instantiated and may contain abstract
methods.
(x) - JVM is the virtual machine that executes Java bytecode and provides platform
independence.
Section B: (30 pts)
1. (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;
2. (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;


3. (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”

4. (3 pts) Write the output of test(1), test(3) and test(5).


public void test(int k) {
String t = "The quick brown fox jumps over the lazy dog";
for (int i = 0; i < k; i++) {
t = t.substring(t.indexOf(" ") + 1);
}
System.out.println(t.substring(0, t.indexOf(" ")));
}
Answer: The output is:
quick
fox
over

5. (3 points) What are uses of final keyword with variable, method and class?
Give an example for each.
Answer:
- Final class can’t be inherited. (1)
Ex. final class person{}
If we write this: class studen extends person {} give an error.
- Final variable mean it is constant and can’t be changed. (1)
Ex. final int x=5;
- Final method can’t be overriden. (1)
Ex. class A{ final void method1(){}
}
classs B extends A{
void method1() {} make an error can’t override final method
}
6. (1 pts) What the difference between usage of throws and throw keyword?
Answer:
Main difference between throw and throws is in there usage and
functionality.
- throws is used in method signature to declare Exception possibly
thrown by any method. (0.5)
- throw is actually used to throw an Exception in Java code.
(0.5)

7.(2 pts) Identify the correct output for the following program fragments. Give the reason.
i.
try
{
int x = 0;
int y = 5 / x;
}
catch (Exception e)
{
System.out.println("Exception");
}
catch (ArithmeticException ee)
{
System.out.println(" Arithmetic Exception");
}
System.out.println("Finished");
a) Exception
b) Arithmetic Exception
c) Compilation fails
d) Finished
Answer:
Compilation fails because ArithmeticException has already been
caught.ArithmeticException is a subclass
of java.lang.Exception, by time theArithmeticException has
been specified it has already been caught by theException class.
ii.
public class FinalBlock {
public static void main(String[] a){
try{
int x = 16/2;
}
catch(Exception ex){
System.out.println("A");
}
finally {
System.out.println("B");
}
try{
int x = 16/0;
}
catch(Exception ex){
System.out.println("C"); }
finally {
System.out.println("D"); }
}
}
Answer:
a) ABCD
b) ABC
c) ACD
d) BCD
8. ( 2 pts) Marks Obtained:
Identify and explain what are OOP Principles used in the following program.
abstract public class Animal {
abstract public void MakeVoice();
}
public class Cat extends Animal {
int LegsNumbers;
public void MakeVoice() {
System.out.println("Meow!");
}
}
public class Dog extends Animal {
String Color;
public void MakeVoice() {
System.out.println("Woof!");
}

public void MakeVoice(String c) {


System.out.println("Woooooooooof!"+ c);
}
}
Answer:
1- Inheritance: Class Cat and Dog extends class Animal.
2- Encapsulation: by using classes Cat, Dog to hold data and methods.
3- Polymorphism: it use Method overriding by overriding to the method
MakeVoice() in class Cat and Dog.
4- Polymorphism: it use Method Overloading by overloading to the method of
MakeVoice(String) in the Dog class.

9) Inheritance (3 pts)
Consider the following code.
class A {
private int x;
public A(int x) {
this.x= x;
}
public void m() {
System.out.println(x-1);
}
}
class B extends A{
private int y;
public B(int y) {
super(y-1);
this.y= y;
}
public void m() {
System.out.println(y+1);
}
}
(i) 1 point What is printed to the console by (new A(3)).m()?
2
(ii) 1 point What is printed to the console by (new B(3)).m()?
4
(iii) 1 point What is printed to the console by ((A)(new B(3))).m()?
4

10. (6 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 C: MySQL connection and SWING
(6 pts) To connect to mysql database using java programming, we must include a library.
What is the name of the library and explain how you include it in your project.

2. Describe the parameters of the following function:


DriverManager.getConnection("jdbc:mysql://localhost:3306/ict","root","root")
3. What is the meaning of the following instruction :
ResultSet rs=stmt.executeQuery("select * from employee");
4. From the above source code what is the name of the database and the table it contains?
5. What is the meaning of the following code? public class Authentification extends JFrame
implements ActionListener {
6. Write a java code to display a login form.

Section C: MySQL connection and SWING


(6 pts)
1. To connect to mysql database using java programming, we must include a library.
What is the name of the library and explain how you include it in your project.

The library required to connect to MySQL database using Java programming is called
"JDBC" (Java Database Connectivity). To include it in your project, you need to follow
these steps:
- Download the JDBC driver for MySQL from the official MySQL website or a
trusted source.
- Add the JDBC driver JAR file to your project's classpath. This can be done by
either copying the JAR file to your project's directory and adding it to the build path in
your IDE, or by specifying the JAR file location in the classpath configuration of your
project.
2. DescribeDescribe the parameters of the following function:
DriverManager.getConnection("jdbc:mysql://Mocalhost:3306/ict", "root", "root")
- `jdbc:mysql://localhost:3306/ict`: This specifies the URL of the MySQL database
server. Here, "localhost" represents the hostname or IP address of the server, "3306" is
the port number, and "ict" is the name of the database.
- `"root"`: This is the username used to connect to the MySQL database.
- `"root"`: This is the password associated with the username.

3. What is the meaning of the following instruction:


ResultSet rs=stmt.executeQuery("'select * from employee"):
The instruction `ResultSet rs = stmt.executeQuery("select * from employee")` executes
a SQL query to retrieve data from the "employee" table in the database. It selects all
columns and rows from the "employee" table and stores the result in the `ResultSet`
object called `rs`.

4. From the above source code what is the name of the database and the table it contains?
From the given source code, the name of the database is "ict" and the table it contains
is "employee".

5. What is the meaning of the following code? public class Authentification extends
JFrame implements ActionListener {
The code `public class Authentification extends JFrame implements ActionListener`
defines a Java class named "Authentification". It extends the `JFrame` class, which
means it inherits the functionality of a JFrame window. The class also implements the
`ActionListener` interface, indicating that it can handle events triggered by user
actions.

6. Write a java code to display a login form.


```java
import javax.swing.*;

public class LoginForm extends JFrame {


private JLabel lblUsername;
private JLabel lblPassword;
private JTextField txtUsername;
private JPasswordField txtPassword;
private JButton btnLogin;

public LoginForm() {
lblUsername = new JLabel("Username:");
lblPassword = new JLabel("Password:");
txtUsername = new JTextField();
txtPassword = new JPasswordField();
btnLogin = new JButton("Login");

setLayout(new GridLayout(3, 2));


add(lblUsername);
add(txtUsername);
add(lblPassword);
add(txtPassword);
add(btnLogin);

setTitle("Login Form");
setSize(300, 150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> new LoginForm());
}
}
This code creates a simple login form using Swing components. It includes labels for
username and password, text fields for user input, and a login button. The form is
displayed as a JFrame window when the program is executed.

Section D (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