0% found this document useful (0 votes)
12 views9 pages

Compre Sol

The document discusses a comprehensive exam for an object oriented programming course. It includes 7 questions testing concepts like class diagrams, sequence diagrams, exceptions, collections, generics and inner classes.

Uploaded by

Nitish Putrevu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views9 pages

Compre Sol

The document discusses a comprehensive exam for an object oriented programming course. It includes 7 questions testing concepts like class diagrams, sequence diagrams, exceptions, collections, generics and inner classes.

Uploaded by

Nitish Putrevu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Birla Institute of Technology & Science, Pilani - K.K.

Birla Goa Campus


Department of CS-IS
First Semester, 2015-16 CS F213 Object Oriented Programming 03.12.2015
Time: 2:00 PM - 5:00 PM Comprehensive Exam (Closed Book) Max. Marks: 90

Solutions
1. Class Diagram (15M)
Draw a class diagram with appropriate attributes (operations need not be shown) for the credit card system out-
lined below. Clearly show the multiplicity and qualifiers, if any of each association.
An institution may issue many credit card accounts, each identified by an account number. Each account has a
maximum credit limit, a current balance, and a mailing address. The account serves one or more customers who
reside at a mailing address. The institution periodically issues a statement for each account. The statement lists a
payment due date, finance charge, and minimum payment. The statement itemizes various transactions that have
occured throughout the billing interval: cash advances, interest charges, purchases, fees, and adjustments to the
account. The name of the merchant is printed for each purchase.

Ans:

2. Sequence Diagram (10M)


In modeling a course of a university, lets say that you decided to put course feedback collection process in feed-
back() method of Course class. The method ends up using studentRep, students, and forms objects. ARC acts
as a static class with a useful method named feedbackDeposit(). Both students (a collection) and studentRep
are objects of type Student. Interesting methods of Student class are: emptyForm(), fillForm() and filledForm().
Only studentRep object can issue empty forms and collect filled forms. student objects take empty form from
studentRep, fill the form and return the filled form to studentRep again. studentRep waits for return of filled forms
from all students and then deposits the filled forms in ARC.
Draw a sequence diagram for the work done in feedback() method.
Ans:

3. Objects and Interfaces (4M)


Correct the mistakes in the given Java code. Provide your answers in the space given below.
a) public interface SomethingIsWrong { public interface SomethingIsWrong {
void aMethod(int aValue) { void aMethod(int aValue);
System.out.println("Hi Mom"); }
} //OR
} public class SomethingIsWrong {
void aMethod(int aValue) {
System.out.println("Hi Mom");
}
}

b) public class SomethingIsWrong { The code never creates a Rectangle object.


public static void main(String[] args) { With this simple program, the compiler gener-
Rectangle myRect; ates an error. However, in a more realistic situ-
myRect.width = 40; ation, myRect might be initialized to null in one
myRect.height = 50; place, say in a constructor, and used later. In
System.out.println("myRect’s area is " that case, the program will compile just fine,
+ myRect.area()); but will generate a NullPointerException at run-
} time.
} Rectangle myRect = new Rectangle();

4. Objects (3 × 2M = 6M)
Identify the following statements as TRUE/FALSE. Circle the appropriate answer for each question.
(a) Java downcasts automatically, but you must explicitly upcast. (FALSE)
(b) The rules for upcasting and downcasting depend upon whether classes are declared public, protected, or
private. (FALSE)
(c) As the toString() method is defined in the Object class, System.out.println can be used to print any object.
(TRUE)
5. Local Classes and Exceptions (10M)
Write code in the identified locations (a), (b), (c) and (d) to print the required output. Each method can’t have more
than one print statement.
abstract class Musician {
abstract public void createRaga();
protected void recite(){ System.out.println("Musician:Recite"); }
public void concert(){ createRaga(); recite(); }
}

//(a)--->

class AdaptableMusician {
private String genre;
public AdaptableMusician(String genre){ this.genre = genre; }
public void createMusic() ______(b)--->__________________{

//(c)--->

}
public static void main(String[] args) __________(d)--->__________________{
AdaptableMusician salim = new AdaptableMusician("Classical");
salim.createMusic();
AdaptableMusician coltrane = new AdaptableMusician("Jazz");
coltrane.createMusic();
//any other music genre results in "UnSupportedGenre" exception
AdaptableMusician elvis = new AdaptableMusician("Rock");
elvis.createMusic();
}
}
/*
output:
-------
Classical anonymous: Experimental, Create Raga, Recite
Jazz anonymous: Create Quartet, Recite
Exception in thread "main" UnSupportedGenre
at AdaptableMusician.createMusic ....
*/
Ans:
abstract class Musician {
abstract public void createRaga();
protected void recite(){ System.out.println("Musician:Recite"); }
public void concert(){
createRaga();
recite();
}
}

class UnSupportedGenre extends Exception {}

class AdaptableMusician {
private String genre;
public AdaptableMusician(String genre){ this.genre = genre; }

public void createMusic() throws UnSupportedGenre{


Musician m = null;
if (genre.equals("Classical")) {
m = new Musician(){
public void createRaga(){
experimental();
System.out.print(", Create Raga");
}
public void experimental(){
System.out.print("Classical anonymous: Experimental");
}

@Override
protected void recite(){ System.out.println(", Recite"); }
@Override
public void concert(){
createRaga();
recite();
}
};
}
else if (genre.equals("Jazz")) {
m = new Musician(){
public void createRaga(){
System.out.print("Jazz anonymous: Create Quartet");
}

@Override
protected void recite(){ System.out.println(", Recite"); }
@Override
public void concert(){
createRaga();
recite();
}
};
} else
throw new UnSupportedGenre();

m.concert();
}

public static void main(String[] args) throws UnSupportedGenre{


AdaptableMusician salim = new AdaptableMusician("Classical");
salim.createMusic();
AdaptableMusician coltrane = new AdaptableMusician("Jazz");
coltrane.createMusic();
//any other music genre results in "UnSupportedGenre" exception
AdaptableMusician elvis = new AdaptableMusician("Rock");
elvis.createMusic();
}
}
6. Collections (10M)
Draw the class diagrams of HashMap, ArrayList classes, and ListIterator interface. Clearly show all the appropriate
methods.
Ans: only the relevant methods of HashMap, ArrayList and ListIterator need to be shown.
Hashmap:

(a) Map interface (b) Hashmap class

ArrayList:

ListIterator:
7. Generics + Inner classes (20M)
Write Java code to satisfy the given class diagram; next() method of ReverseArrayIterator must throw No-
SuchElementException exception if the stack is empty; remove() method of ReverseArrayIterator must always
throw UnsupportedOperationException exception.

Ans:

package java.lang;

import java.util.Iterator;

public interface Iterable<T> {


Iterator<T> iterator();
}

package java.util;

public interface Iterator<E> {


boolean hasNext();
E next();
void remove();
}

import java.util.Iterator;
import java.util.NoSuchElementException;

public class FixedCapacityStack<Item> implements Iterable<Item> {


private Item[] a;
private int N;

public FixedCapacityStack(int capacity) {


a = (Item[]) new Object[capacity];
N = 0;
}

public boolean isEmpty() { return N == 0; }


public void push(Item item) { a[N++] = item; }
public Item pop() { return a[--N]; }
public Iterator<Item> iterator() { return new ReverseArrayIterator(); }

//write the code for the ReverseArrayIterator inner class


public class ReverseArrayIterator implements Iterator<Item> {
private int i = N-1;

public boolean hasNext() {


return i >= 0;
}

public Item next() {


if (!hasNext()) throw new NoSuchElementException();
return a[i--];
}

public void remove() {


throw new UnsupportedOperationException();
}
}

8. Concurrency (5M-Bonus)
Write Java code to protect the operation of pop() method using Lock. Similarly, protect the operation of push()
method using synchronized.
Ans:
pop() method:
Lock mylock = new ReentrantLock();
...
public Item pop() {
mylock.lock();
try {
--N;
} finally {
mylock.unlock();
}
return a[N];
}
push() method:
public synchronized void push(Item item) { a[N++] = item; }
9. Concurrency (15M)
Consider the JumbleNames.java program given in the next sheet. The task is to print firstName, makes the
thread sleep for delay time period, and then prints secondName in an infinite loop. The task must handle any
interrupts received by the thread. Upon receiving an interrupt, the task must come out of infinite loop and finish
its work. Create three threads to drive three tasks, namely JumbleNames("Chandragupta ", "Maurya ", 200L),
JumbleNames("Krishna ", "Devaraya ", 300L), and JumbleNames("James ", "Carse ", 500L).

import java.io.IOException;
public class JumbleNames implements Runnable {
private String firstName,secondName;
private long delay;
public JumbleNames(String firstName, String secondName, long delay) {
this.firstName = firstName;
this.secondName = secondName;
this.delay = delay; }
public void run() {
//define the task
//(a)--->
}
public static void main(String[] args) {
//create three threads to drive three tasks
//(b)--->

//set threads in daemon mode


//(c)--->

//start the threads


//(d)--->

System.out.println("Press Enter when you have had enough...\n");


//try-catch block waiting for any key press to end the main
try {
System.in.read();
System.out.println("Enter pressed...\n");

} catch (IOException e) {
System.err.println(e);
}
System.out.println("Ending main()");
return;
}
}

Ans:
import java.io.IOException;

public class JumbleNames implements Runnable {


private String firstName,secondName;
private long delay;

public JumbleNames(String firstName, String secondName, long delay) {


this.firstName = firstName;
this.secondName = secondName;
this.delay = delay;
}

public void run() {


int i=10;
try {
while(i-- > 0) {
System.out.print(firstName);
Thread.sleep(delay);
System.out.print(secondName+"\n");
}
} catch(InterruptedException e) {
System.out.println(firstName + secondName + e);
}
}

public static void main(String[] args) {


Thread first = new Thread(new JumbleNames("Chandragupta ", "Maurya ", 200L));
Thread second = new Thread(new JumbleNames("Krishna ", "Devaraya ", 300L));
Thread third = new Thread(new JumbleNames("James ", "Carse ", 500L));

first.setDaemon(true);
second.setDaemon(true);
third.setDaemon(true);

first.start();
second.start();
third.start();

System.out.println("Press Enter when you have had enough...\n");


//try-catch block waiting for any key press to end the main
try {
System.in.read();
System.out.println("Enter pressed...\n");

} catch (IOException e) {
System.err.println(e);
}
System.out.println("Ending main()");
return;
}

}
10. Concurrency (5M-Bonus)
Ignoring the daemon status requirement of part-(c) of question #9, rewrite parts-(b) and (d) using Executors.
Make sure you use the cached thread pool option and provide for graceful shutdown.
Ans:
ExecutorService cachedPool = Executors.newCachedThreadPool();
cachedPool.execute(new JumbleNames2("Chandragupta ", "Maurya ", 200L));
cachedPool.execute(new JumbleNames2("Krishna ", "Devaraya ", 300L));
cachedPool.execute(new JumbleNames2("James ", "Carse ", 500L));
cachedPool.shutdown();

You might also like