0% found this document useful (0 votes)
17 views16 pages

Compre CS F213 OOPS Solution Key 2022-23

The document is a comprehensive examination booklet for the Object Oriented Programming course at Birla Institute of Technology and Science Pilani, Hyderabad Campus. It includes multiple-choice questions and coding problems, with a total weightage of 40% for the exam, which is closed book and spans 180 minutes. Additionally, it outlines a project to create a user interface application for validating BITS email and password, along with a section discussing JDBC database drivers.

Uploaded by

anshul das
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)
17 views16 pages

Compre CS F213 OOPS Solution Key 2022-23

The document is a comprehensive examination booklet for the Object Oriented Programming course at Birla Institute of Technology and Science Pilani, Hyderabad Campus. It includes multiple-choice questions and coding problems, with a total weightage of 40% for the exam, which is closed book and spans 180 minutes. Additionally, it outlines a project to create a user interface application for validating BITS email and password, along with a section discussing JDBC database drivers.

Uploaded by

anshul das
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/ 16

Name: ID: 2 0 H

Birla Institute of Technology and Science Pilani


Hyderabad Campus
Compre Question Booklet for Object Oriented Programming
CS F213 (Even Sem 2022-23)
Exam type: Closed Book
Weightage: 40% Date: 18th May 2023
Full Marks: 80 Time: 180 minutes

Section A 15x2=(30 marks)


● Answer the following MCQ, each correct attempt will be awarded 2 marks (max marks 2x15= 30)
● Attempt by putting a tick mark 🗸 (only no other forms will be considered) on the correct option
● Each wrong attempt will lead to a negative marking of 0.5 marks

1 import java.util.regex.*; A 0
. public class Archie {
public static void main(String[] args) { B 3
Pattern p = Pattern.compile(args[0]);
C 4
Matcher m = p.matcher(args[1]);
int count = 0; D Compilation fails
while(m.find())
count++;
System.out.print(count);
}
}
And given the command line invocation:
java Archie "\d+" ab2c4d67
What is the result?

2 import java.io.*; A pcc


. class Player
{ B pcp
Player()
C pcpc
{
System.out.print("p"); D Compilation Fails
}}
class CardPlayer extends Player implements Serializable
{
CardPlayer()
{ System.out.print("c"); }
public static void main(String[] args)
{ CardPlayer c1 = new CardPlayer();
try
{
FileOutputStream fos = new FileOutputStream("play.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(c1);
os.close();
FileInputStream fis = new FileInputStream("play.txt");
ObjectInputStream is = new ObjectInputStream(fis);
CardPlayer c2 = (CardPlayer) is.readObject();
is.close();
}
catch (Exception x )
{}
}}
What is the result?

3 import java.util.regex.*; A 01234567


. class Regex2 {
public static void main(String[] args) B 12334567
{
C 01234456
Pattern p = Pattern.compile(args[0]);
Matcher m = p.matcher(args[1]); D Compilation Error
boolean b = false; while(b = m.find())
{
System.out.print(m.start() + m.group());
}
}
}

And the command line: java Regex2 "\d*" ab34ef


What is the result?

4 public class Theory { A The first line of output is abcd abc false
. public static void main(String[]
args) { B The first line of output is abc abc false
String s1 = "abc";
C The first line of output is abc abc true
String s2 = s1;
s1 += "d"; D Compilation error
System.out.println(s1 + " " + s2 + "
" + (s1==s2));

StringBuffer sb1 = new


StringBuffer("abc");
StringBuffer sb2 = sb1;
Name: ID: 2 0 H

sb1.append("d");
System.out.println(sb1 + " " + sb2 +
" " + (sb1==sb2));
}
}

Which one is correct?

5 import java.io.*; A ab
. public class ReadingFor { cd
public static void main(String[] args) {
String s; B abcd
try {
C a
FileReader fr = new FileReader("myfile.txt");
b
BufferedReader br = new BufferedReader(fr); c
while((s = br.readLine()) != null) d
System.out.println(s);
br.flush(); D Compilation error
} catch (IOException e) { System.out.println("io error"); }
}
}

And given that myfile.txt contains the following two lines of data:
ab
cd
What is the result?

6 import java.io.*; A username: fred


. public class Talker {
public static void main(String[] args) { password:
Console c = System.console();
String u = c.readLine("%s", "username: ");
B username: fred
System.out.println("hello " + u);
String pw;
password: 1234
if(c != null && (pw = c.readPassword("%s", "password: ")) != null)
// check for valid password
}} C username: fred
If line 4 creates a valid Console object, and if the user enters fred as a
username and 1234 as a password, what is the result?
} password: 1234

D Compilation fails

7 import java.text.*; A The output is 987.12345 987.12345


. public class Slice {
public static void main(String[] args) { B The output is 987.12346 987.12345
String s = "987.123456";
C The output is 987.12345 987.123456
double d = 987.123456d;
NumberFormat nf = NumberFormat.getInstance(); D The output is 987.12346 987.123456
nf.setMaximumFractionDigits(5);
System.out.println(nf.format(d) + " ");
try {
System.out.println(nf.parse(s));
} catch (Exception e) { System.out.println("got exc"); }
}}

Which one is true?

8 Which resources have their close() method called when this code A No close() methods are
. runs? called.
public static void runQuery(Connection conn) throws SQLException {
try (Statement stmt = conn.createStatement()) { B Only Statement
ResultSet rs = stmt.executeQuery("select * from clowns");
C Only Statement and
rs.next(); }} ResultSet

D Only Statement and


Connection

9 What will be output for the following code? A java


. import java.io.*;
class files B system
{
public static void main(String args[]) C java/system
{
File obj = new File(""/java/system""); D /java/system
System.out.print(obj.getName());
}
}
Name: ID: 2 0 H

10 What will be the output of the following Java A true


. program?
import java.io.*; B false
class filesinputoutput{
C prints number of bytes in file
public static void main(String args[]) {

InputStream obj = new D prints number of characters in the file

FileInputStream("inputoutput.java");
System.out.print(obj.available());
}
}

11. Given the code fragment: A May 04, 2014T00:00:00.000


public static void main(String[] args) {
String date = LocalDate.parse("2014-05-04")
.format(DateTimeFormatter.ISO_DATE_TIME); B 2014-05-04T00:00: 00.000
System. out. println(date);
}
What is the result? C 5/4/14T00:00:00.000

D An exception is thrown at runtime.

What is the output of the following program? A M M M MM M


12
import java.util.regex.*;
B M M M MM m mM
public class RegularEx {
public static void main(String... arg) {
C M Merit Match MM m
Pattern pattern = Pattern.compile("M+", 5);
mM
Matcher matcher = pattern.matcher("M Merit Match MM
m mM");
D M M M MM mM
while (matcher.find())
System.out.print(matcher.group() + " ");
}
}

13 What will be the output of the following code? A 1


import java.util.regex.*;
B 2
public class RegexExample {
public static void main(String[] args) { C 3
String text = "OpenAI is awesome!";
D 4
Pattern pattern = Pattern.compile("\\b(\\w+)\\b");
Matcher matcher = pattern.matcher(text);

int count = 0;
while (matcher.find()) {
count++;
}

System.out.println(count);
}
}

14 Consider code snippet: A The details of all


employees in the
import java.sql.*; "employees" table will be
printed.
public class JDBCTest {
public static void main(String[] args) { B An exception occurred:
try { No suitable driver found
for
String jdbcDriver = "com.mysql.jdbc.Driver"; jdbc:mysql://localhost:330
String databaseUrl = 6/mydb
"jdbc:mysql://localhost:3306/mydb";
C An exception occurred:
String username = "root"; Access denied for user
String password = "password"; 'root'@'localhost' (using
password: YES)

Class.forName(jdbcDriver); D An exception occurred:


Connection connection = Table 'mydb.employees'
DriverManager.getConnection(databaseUrl, username, doesn't exist
password);

Statement statement =
connection.createStatement();
String query = "SELECT * FROM employees";
ResultSet resultSet =
statement.executeQuery(query);

while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
int age = resultSet.getInt("age");

System.out.println("ID: " + id + ", Name: " +


name + ", Age: " + age);
}
Name: ID: 2 0 H

resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
System.out.println("An exception occurred: " +
e.getMessage());
}
}
}

15 Consider code : A An exception is thrown at


public class Threads3 implements Runnable { runtime.
public void run() {
B The code executes and prints
System.out.print("running");
"running".
}
public static void main(String[] args) { C The code executes and prints
"runningrunning".
Thread t = new Thread(new Threads3());
t.run(); D The code executes and prints
"runningrunningrunning".
t.run();
t.start();
}
}
What is the result?

Solution Key:
A B C D

6
7

10

11

12

13

14

15

Section B (60 marks)


Response for the following problems. No extra space is provided so think before you write.
● You may divide the space into two columns to utilize space judiciously
● System.out.println can be written as Sop(), public static void main as PSVM().
● Other than braces and semicolons, any error that may lead to a compilation error will be
penalized.
1. Create a User Interface Application to validate BITS email and password. The application is
developed using Frame with two text fields and two Buttons. One text field accepts email id
and another text field accepts password. Give appropriate labels for the text fields. The two
buttons are named EXIT and SUBMIT. EXIT button closes the application. SUBMIT button
validates the email and password using regular expressions. Only regular expressions should be
used for validation. You can use any Layout manager of your choice to arrange the
components. The same class that implements the Frame can also implement the Event
Handler. An error message is displayed if either email or password is not validated. Note both
email and password are case-sensitive.

BITS email has the following requirements: starts with f or h or p, followed by the year of
admission, followed by 4 numeric digits, followed by hyderabad.bits-pilani.ac.in

BITS password has the following requirements: The password should be 8 characters in length
and It should have at least 1 uppercase, 1 lower case, 1 digit, 1 special character [15 marks].

Rubrics:
Name: ID: 2 0 H

If Frame implementation is correct : 6 marks

Exit Button event handling : 2 marks

Submit Button event handling : 5 marks

Display of error message : 2 marks

Solution:
import java.awt.*;
import java.awt.event.*;
public class LoginValidator extends Frame implements ActionListener{
TextField tf1;
TextField tf2;
Button b1, b2;
LoginValidator(){
Label l1 = new Label("Email");
Label l2 = new Label("Pwd");
tf1 = new TextField();
tf2 = new TextField();
b1 = new Button("Validate");
b2 = new Button("Exit");
b1.addActionListener(this);
b2.addActionListener(this);
add(l1); add(tf1); add(l2); add(tf2);
add(b1); add(b2);
setLayout(new GridLayout(3,2));
setVisible(true);
setSize(300,300);
}
public void actionPerformed(ActionEvent e) {
String emailpattern =
"^(p|f|h)(2019|2020|2021|2022|2023)(?=.*[0-9]).{4}@hyderabad.bits-pilani.ac.in$";
String pwdpattern =
"^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,}$";
if(b2.hasFocus()) {
System.exit(0);
}
if(b1.hasFocus()) {
if(tf1.getText().matches(emailpattern)&&tf2.getText().matches(pwdpattern)) {
tf1.setText("valid password");
tf2.setText("valid password");
}
else {
tf1.setText("invalid email");
tf2.setText("invalid password");
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new LoginValidator();
}
}
2. Explain the different types of JDBC database drivers available. Explain each of them in on
sentence [4 marks]

Solution: 1 marks per correct type and explanation

Fill in the blanks as appropriate to complete the following java code [1x11=11 marks]

import java.sql.*;

public class JdbcInsertTest {

public static void main(String[] args) {

try (

Connection conn = DriverManager.getConnection(


"jdbc:mysql://localhost:3306/ebookshop?allowPublicKeyRetrieval=true&useSSL=false&serverTimezo
ne=UTC",

"myuser", "xxxx");

Statement stmt = conn.createStatement();

// DELETE records with id>=3000 and id<4000

String sqlDelete = "delete from books where id >= 3000 and id < 4000";

// INSERT a record

String sqlInsert = "insert into books values (3001, 'Gone Fishing', 'Kumar', 11.11, 11)";

// INSERT multiple records 1st record is 3002, 'Gone Fishing 2', 'Kumar', 22.22, 22; 2nd record is
3003, 'Gone Fishing 3', 'Kumar', 33.33, 33
Name: ID: 2 0 H

sqlInsert = "insert into books values "

+ "(3002, 'Gone Fishing 2', 'Kumar', 22.22, 22),"

+ "(3003, 'Gone Fishing 3', 'Kumar', 33.33, 33)";

// Step 3 & 4: get all the data from book to check the changes

String strSelect = "select * from books";

// Print all selected data

while(rset.next()) { // Move the cursor to the next row

System.out.println(rset.getInt("id") + ", "

+ rset.getString("author") + ", "

+ rset.getString("title") + ", "

+ rset.getDouble("price") + ", "

+ rset.getInt("qty"));

} catch(SQLException ex) {

ex.printStackTrace();

} // Step 5: Close conn and stmt - Done automatically by try-with-resources

3. Sentinel License Development Kit (Sentinel LDK) is a Software Digital Rights Management
(DRM) solution by SafeNet Inc. that delivers strong copy protection, protection for Intellectual
Property (IP), and secure and flexible licensing. Sentinel LDK separates licensing and
production processes (implemented with Sentinel EMS) from the software protection process
(implemented with Sentinel Licensing API or Sentinel LDK Envelope). Sentinel EMS is a
web-based graphical application provided as part of Sentinel LDK that is used to perform a
range of functions required to manage the licensing, production, distribution, customer support,
and maintenance of protected applications. This application is a role-based application designed
to manage the business activities required to implement and maintain Sentinel LDK in the
organization which needs to protect its software. Sentinel EMS Server maintains a database
containing a wide range of information, including data related to product features, licenses,
sales, orders, and customers.

Product Manager defines Features and Products. Users assigned the Development role can
fulfill one of the following development-related activities: Generate bundles of Provisional (Trial)
Products Generate a customized Sentinel LDK Run-time Environment (RTE) installer file
Customize the Sentinel Remote Update System utility (RUS utility) Entitlement Manager defines
and manages customers, and also enters and manages entitlements. Customer Services roles
can manage customers the same way as Entitlement Manager does, and can also manage
Product activation. For entitlements that generate Product Keys, the customer receives an email
from Sentinel EMS that contains the keys. The customer is able to log in to the EMS Customer
Portal using the Product Key in order to activate the Product.

Draw a use case diagram below shows some simplified view of software licensing use cases
supported by Sentinel EMS Application (shown as «Application» stereotyped subject). The
Sentinel EMS handles three major workflows: license planning, order processing and
production, and activation of trial software.[10 marks]

Solution: 1 marks per correct anchor and their functionality


Name: ID: 2 0 H

4. Given below are two incomplete java files, RunnableExample.java and RunnableTask.java
If you first compile “RunnableTask.java” and then compile “RunnableExample.java” and then
execute “java RunnableExample” then the following output is obtained:

Create Task to get content from files/test1.txt


Create Task to get content from files/test2.txt
Create Task to get content from files/test3.txt
Create Task to get content from files/test4.txt
Create Task to get content from files/test5.txt
File files/test1.txt retrieved data: Hello BITS!
File files/test1.txt retrieved data: Hello BITS!Hello Hyderabad.
File files/test4.txt retrieved data: Have a nice day!
File files/test3.txt retrieved data: Food at Yumpy is good!
File files/test2.txt retrieved data: You're awesome!
File files/test3.txt retrieved data: Food at Yumpy is good!may not be great
File files/test2.txt retrieved data: You're awesome!You may not know that
File files/test5.txt retrieved data: Look forward to talking with you.
File files/test4.txt retrieved data: Have a nice day!I know you won't
File files/test5.txt retrieved data: Look forward to talking with you.Please don't
come with wierd requests.
File files/test2.txt retrieved data: You're awesome!You may not know thatbut you are!
File files/test3.txt retrieved data: Food at Yumpy is good!may not be greatbut
definitely not terrible!
File files/test5.txt retrieved data: Look forward to talking with you.Please don't
come with wierd requests.I hope you score the full marks
File files/test4.txt retrieved data: Have a nice day!I know you won'tBut there is no
harm in wishing!!!
File files/test5.txt retrieved data: Look forward to talking with you.Please don't
come with wierd requests.I hope you score the full marksBest of luck :)
Result:
Hello BITS!Hello Hyderabad.
You're awesome!You may not know thatbut you are!
Food at Yumpy is good!may not be greatbut definitely not terrible!
Have a nice day!I know you won'tBut there is no harm in wishing!!!
Look forward to talking with you.Please don't come with wierd requests.I hope you
score the full marksBest of luck :)

The files that are read are:

test1.txt

Hello BITS!
Hello Hyderabad.

test2.txt

You're awesome!
You may not know that
but you are!

test3.txt

Food at Yumpy is good!


may not be great
but definitely not terrible!

test4.txt

Have a nice day!


I know you won't
But there is no harm in wishing!!!

test5.txt

Look forward to talking with you.


Please don't come with wierd requests.
I hope you score the full marks
Best of luck :)

Now fill in the gaps:

RunnableExample.java

import java.util.ArrayList;
import java.util.List;

public class RunnableExample {


public static void main(String[] args) {
// create tasks
List<RunnableTask> tasks = new ArrayList<>();
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 5; i++) {
RunnableTask task = new RunnableTask("test" + (i + 1) + ".txt");
Thread t = new Thread(task);
t.start();
tasks.add(task);
threads.add(t);
}

try {
for (int i = 0; i < 5; i++) {
threads.get(i).join();
}
} catch (InterruptedException e) {
e.printStackTrace();
}

String content = "";


for (int i = 0; i< 5; i++) {
//two marks, rest are all 1
content += tasks.get(i).getContent() + System.lineSeparator();
}

System.out.println("Result:");
System.out.println(content);
}
}
Name: ID: 2 0 H

RunnableTask.java

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;

public class RunnableTask implements Runnable {


private String filename;
private String content;

public RunnableTask(String filename) {


this.filename = filename;
this.content = "";
System.out.println("Create Task to get content from " + filename);
}

public String getFileName() {


return filename;
}

public void run() {


try {
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir, filename);
File file = path.toFile();

BufferedReader br = new BufferedReader(new FileReader(file));

String line;
while ((line = br.readLine()) != null) {
content += line;
System.out.println("File "+this.filename+" retrieved data:
"+ content);
}

} catch (FileNotFoundException e1) {


e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
public String getContent() { return content; }
}
Rough work
—---------------------------------

You might also like