0% found this document useful (0 votes)
50 views12 pages

University Cs3391

The document is a university question paper for the Object Oriented Programming course at Indra Ganesan College of Engineering, detailing course outcomes and a series of questions divided into two parts. Part A consists of short answer questions worth 20 marks, while Part B includes longer questions worth 65 marks, covering various Java programming concepts such as classes, inheritance, exception handling, and GUI development. The paper is designed for second-year IT students and spans a total of 100 marks.

Uploaded by

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

University Cs3391

The document is a university question paper for the Object Oriented Programming course at Indra Ganesan College of Engineering, detailing course outcomes and a series of questions divided into two parts. Part A consists of short answer questions worth 20 marks, while Part B includes longer questions worth 65 marks, covering various Java programming concepts such as classes, inheritance, exception handling, and GUI development. The paper is designed for second-year IT students and spans a total of 100 marks.

Uploaded by

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

Register Number:

INDRA GANESAN COLLEGE OF ENGINEERING


(AN AUTONOMOUS INSTITUTION)
IG Valley, Manikandam, Tiruchirappalli, Tamil Nadu – 620 012, India
(Approved by AICTE, New Delhi and affiliated to Anna University, Chennai)
University question paper Date 31/12/2024 Marks 100
Course code CS3391 Course Title Object Oriented Programming
Regulation 2024 Duration 3 HOURS Academic Year 2024-2025
Year II Semester III Department IT
COURSE OUTCOMES
CO.1 :Apply the concepts of classes and objects to solve simple problems
CO.2 :Develop programs using inheritance, packages and interfaces
CO.3 :Make use of exception handling mechanisms and multithreaded model to solve real world problems
CO.4 :Build Java applications with I/O packages, string classes, Collections and generics concepts
CO.5 :Integrate the concepts of event handling and JavaFX components and controls for developing GUI based applications
Q.No. Question CO BTS
PART -A
(Answer all the Questions 10 x 2 = 20 Marks)
1 what is the difference between mthods aand constructor in table form
Aspect Method
Constructor
Defines behavior or actions to be performed on an
Purpose Initializes an object when it is created.
object or class.
Automatically called when an object is
Invocation Explicitly called using an object or class.
instantiated.
Return Type Can have a return type (e.g., int, String, void). Does not return a value.
Name Can have any valid name, usually based on the action. Must have the same name as the class.
2 Java Lanugage is platform independent justify your answer

 The core idea behind Java's platform independence is the principle of "Write Once, Run
Anywhere"..
 The key to this lies in Java's use of bytecode. Java code is first compiled into an intermediate
form called bytecode
 .
3 What are the four types of access modifiers CO1 K1
Access Modifier Visibility
public Accessible from anywhere (any class or package).
private Access
protectedble only
Accessible within the same package and by subclasses (even in different
within the same class.
packages).
Default (Package-
Accessible only within the same package.
Private)

4 Define package CO4 K2


In Java, a package is a namespace that organizes a set of related classes and interfaces. Packages
help avoid name conflicts and make it easier to manage and maintain a large codebase by grouping
similar classes and functions together.
5 Name any four java built in exception CO5 K3
 Arithmetic Exception
 Null Pointer Exception
 Array Index Out Of Bounds Exception
 File Not Found Exception
6 Difference between multi threading and multi tasking CO2 K1
Aspect Multithreading Multitasking
Definition Multithreading is the ability of a CPU (or a single Multitasking is the ability of a CPU
core) to execute multiple threads concurrently to execute multiple processes

Page 1 of 12
within a single process. concurrently.
7 Why do we need generics in java CO2 K1
Generics in Java provide a way to write type-safe code that works with objects of various types
while still allowing compile-time checks for errors. By using generics, Java allows you to write
more flexible, reusable, and maintainable code without losing type safety .
8 What is the character stream CO3 K2
Character streams are part of the java.io package. They consist of Reader and Writer classes, each
of which has specific subclasses for handling text.
9 What do u mean event handling CO3 K3
Event handling in Java refers to the mechanism that allows an application to respond to user
interactions or other events (such as mouse clicks, keyboard input, window resizing, etc.).
10 Differentiate between HBOX and VBOX CO4 K1
H Box (Horizontal Box V Box (Vertical Box )

Arranges child elements horizontally Arranges child elements vertically

Best used when you want to arrange Best used when you want to arrange
components top to bottom components left to right.

PART -B
(Answer all the Questions 5 x 13 = 65 Marks)
11a

List and explain various features of java

Java is one of the most widely used programming languages, known for its platform independence,
robust security features, and simplicity. Below is a list of various features of Java along with
explanations:

1. Platform Independence:

2. Object-Oriented Programming (OOP):

3. Simple and Easy to Learn :

4. Multithreading.

:5. Distributed Computing Example:

6. High Performance:.

7. Rich API (Application Programming Interface):.

8. Automatic Memory Management (Garbage Collection)

9. Dynamic (Runtime Linking).

10. Platform-Independent GUI (Swing, JavaFX)

11)b)What is the array write a java program demonstrating the use of one –
dimensional array in java

An array in Java is a data structure that stores a fixed-size collection of elements of the same type.,

Page 2 of 12
strings, objects, etc.

One-Dimensional Array:

A one-dimensional array is a linear collection of elements, where each element is accessed by its
index.

Syntax for declaring a one-dimensional array:

Java Program Demonstrating the Use of One-Dimensional Array:

OR
11b Why do we need Static members how to access with example
1. .

Types of Static Members:

1. Static Variables (Class Variables): These are variables shared by all instances of the class.
2. Static Methods: These are methods that can be called without creating an instance of the
class.
3. Static Blocks: These are used for static initialization of a class.
4. Static Classes: These are inner classes declared as static.

Accessing Static Members:

 Static Variables: Can be accessed using the class name or through an object reference.
 Static Methods: Can be called using the class name or through an object reference, but it's
recommended to use the class name.

Example: Javaprogram

11)b)iiProperties of constructor

constructor in Java is a special type of method used to initialize objects. When an object of a class is
created, the constructor is automatically invoked to initialize the object's fields.

1. Same Name as Class:

 .

Example:

2.No Return Type:

3. Called Automatically:

Example:

4. Can Have Parameters (Parameterized Constructor):.

Example:

5. Default Constructor (No Arguments):

Example

Page 3 of 12
:

12a Illustrate how to add classes in package and how to access these class in package. CO2 K2

In Java, packages are used to group related classes, interfaces, and sub-packages together. A
package helps in organizing the project structure and avoiding class name conflicts.

Steps to Create a Package, Add Classes to It, and Access Classes in a Package

1. Creating a Package

2. Adding Classes to a Package

3. Accessing Classes in a Package

To access the classes in the package, you need to use:

 Import statement: To import a specific class or the entire package.


 Fully qualified name: To reference the class without using import.

Example 1: Creating a Package and Adding Classes to It

1. Creating the Package

2.. Accessing Classes in the Package

OR
12b Explain interface with example CO2 K3

n interface in Java is a reference type, similar to a class, but it can contain only abstract methods,
default methods, static methods, and constants (final variables).

Syntax to Define an Interface:

Example of an Interface in Java:

Step 1: Define the Interface

13a i)Define exception and explain its different types with example. CO3 K2

An exception in Java is an event that disrupts the normal flow of the program's execution.

Types of Exceptions in Java

Exceptions in Java can be classified into two main categories:

1. Checked Exceptions (Compile-time exceptions)


2. Unchecked Exceptions (Runtime exceptions)

Exception Handling in Java

Java provides the following mechanism to handle exceptions:

Page 4 of 12
1. try: The block where exceptions might occur.
2. catch: The block that catches the exception and handles it.
3. finally: A block that is always executed, whether or not an exception occurred.
4. throw: Used to explicitly throw an exception.
5. throws: Used in method declarations to specify that the method might throw exceptions.

Example Program

13a)ii)What is final keyword? Explain with an example?

1. Final Variable.

public class FinalVariableExample {


public static void main(String[] args) {
final int MAX_SIZE = 100; // Declaring a final variable

// MAX_SIZE = 200; // Error: Cannot assign a value to a final variable

System.out.println("Max Size: " + MAX_SIZE); // Output: Max Size: 100


}
}

2.Final Method

A method that is declared final cannot be overridden by subclasses. This is used to prevent a method
from being modified or redefined in derived classes.

 Example Program:

OR
13b Differentiate string buffer and string class CO3 K2

The String and String Buffer


classes in Java are both used for handling text, but they
have different behaviors and use cases. Below is a detailed comparison between
String and StringBuffer.

Feature String StringBuffer


String Buffer is mutable. You can
String is immutable. Once created, the value
Immutability modify the content of a StringBuffer
of a String object cannot be changed.
object after it is created.
Because String is immutable, every time you
String Buffer is more efficient for
modify a String (e.g., concatenation), a new
repeated modifications, as it does not
Performance String object is created. This makes it less
create new objects each time; instead, it
efficient in scenarios involving repeated
modifies the existing object.
modifications.
Since String is immutable, operations like StringBuffer uses less memory in
concatenation result in the creation of scenarios where the content is modified
Memory
multiple objects, which consumes more repeatedly. It dynamically adjusts its
Consumption
memory when dealing with many size and does not create new objects for
modifications. every change.
String Buffer is thread-safe by default
String is inherently thread-safe because its
because it uses synchronized methods
Thread Safety state cannot be changed once created
for operations, ensuring it can be safely
(immutable).
accessed by multiple threads.
Methods String has methods like concat(), substring(), String Buffer has methods like
Available charAt(), replace(), etc., but it does not append(), insert(), delete(), reverse(),
Page 5 of 12
Feature String StringBuffer
and replace(), which allow modification
support direct modification.
of the buffer's content.
String Buffer is suitable for scenarios
String is ideal for handling fixed or constant
where you need to modify the string
Usage strings, especially when the content is not
frequently (e.g., in loops or when
going to change.
manipulating large texts).

1313bii)Write a java program to fid the given string is palindrome or not

A palindrome is a string that reads the same forward and backward, such as "madam", "racecar", or
"level".

Java Program to Check if a String is Palindrome:

Example program

14a Write a java program to read data from file and to write a data toa a file CO4 K3
import java.io.*;

public class FileReadWriteExample {

// Method to read data from a file


public static void readFromFile(String filename) {
// Create a BufferedReader to read the file
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
// Read line by line
while ((line = reader.readLine()) != null) {
System.out.println(line); // Print each line
}
} catch (IOException e) {
System.out.println("An error occurred while reading the file.");
e.printStackTrace();
}
}

// Method to write data to a file


public static void writeToFile(String filename, String data) {
// Create a BufferedWriter to write to the file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filename))) {
writer.write(data); // Write data to the file
System.out.println("Data written to the file successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
}
}
public static void main(String[] args) {
String readFile = "input.txt"; // File to read from
String writeFile = "output.txt"; // File to write to

// Writing some sample data to the file


String dataToWrite = "Hello, this is a test of writing data to a file.\nThis is the second line of
data.";
writeToFile(writeFile, dataToWrite);

// Reading data from the file


System.out.println("\nReading data from the file:\n");
readFromFile(readFile); // Try to read the input.txt file
Page 6 of 12
}
}

14b Describe how to implement runnable interface for creating and starting CO4 K3
threads
// Class that implements Runnable interface
class MyRunnable implements Runnable {
@Override
public void run() {
// Code that will be executed by the thread
System.out.println(Thread.currentThread().getName() + " is running...");
try {
// Simulating some work with a sleep
Thread.sleep(1000); // 1 second
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
System.out.println(Thread.currentThread().getName() + " has finished.");
}
}

public class RunnableExample {


public static void main(String[] args) {
// Create an instance of the MyRunnable class
MyRunnable myRunnable = new MyRunnable();

// Create two Thread objects, passing the Runnable object


Thread thread1 = new Thread(myRunnable, "Thread-1");
Thread thread2 = new Thread(myRunnable, "Thread-2");

// Start both threads


thread1.start();
thread2.start();
}
}
Define threads . Describe in detail about thread life cycle

Thread Life Cycle

The lifecycle of a thread describes the various states a thread can be in during its existence. A thread
can be in one of the following states at any point during its lifetime:

1. New (Born) State


2. Runnable (Ready) State
3. Blocked/Waiting State
4. Timed Waiting State
5. Terminated (Dead) State.

1. New (Born) State


Thread t = new Thread();

At this point, the thread is in the new state.

2. Runnable (Ready) State


t.start(); // Thread moves to the runnable state

3. Blocked / Waiting State


synchronized (object) {
// Thread might enter blocked state if another thread holds the lock
}
 Waiting for Input: A thread might wait for input or I/O operations, entering a waiting state
until the necessary resources are available.

4. Timed Waiting State.


Page 7 of 12
 sleep(long milliseconds): The thread is paused for a given number of milliseconds.
 join(long milliseconds): A thread waits for another thread to finish for a given time.
 wait(long milliseconds): The thread waits for a specific amount of time while holding the

The diagram below shows the flow of thread states:

New -> Runnable -> Running -> Terminated


| |
Blocked/Waiting
|
Timed Waiting

15a State and explain the basic of AWT event handling in detail CO5 K3
import java.awt.*;
import java.awt.event.*;

public class AWTEventHandlingExample {


// Constructor for setting up GUI components
public AWTEventHandlingExample() {
// Create a frame (window)
Frame frame = new Frame("AWT Event Handling Example");

// Create a button
Button button = new Button("Click Me");

// Register an ActionListener for the button


button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Display a message when the button is clicked
System.out.println("Button was clicked!");
}
});

frame.setLayout(new FlowLayout());
frame.add(button);

// Set the size of the frame


frame.setSize(300, 200);

frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0); // Exit the application
}
});
}

public static void main(String[] args) {


// Create an instance of the event handling class to display the GUI
new AWTEventHandlingExample();
}
}

OR
15b With neat example, explain java AWT Menu bars and menu items CO5 K3
import java.awt.*;
import java.awt.event.*;

public class AWTMenuExample {

// Constructor for setting up the GUI


public AWTMenuExample() {
// Create a frame (window)
Frame frame = new Frame("AWT Menu Example");

// Create a MenuBar
MenuBar menuBar = new MenuBar();
Page 8 of 12
// Create the 'File' menu
Menu fileMenu = new Menu("File");

// Create menu items for 'File' menu


MenuItem newItem = new MenuItem("New");
MenuItem openItem = new MenuItem("Open");
MenuItem saveItem = new MenuItem("Save");
MenuItem exitItem = new MenuItem("Exit");
// Add action listeners to menu items
newItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("New File Selected");
}
});

PART- C (Answer all the Questions 1 x 15 = 15 Marks)


16a CO1 K4

Declare and abstact class to represent a bank account with data memer’s name account
number address and abstract methods withdraw and deposit. Method display is needed to show
balance . Derive a subclass Savings
(i) Account and add the following details: return on inverstment and the method
calc() to show the amount in the account and slow the use of with draw nd
deposit abstract methods

// Abstract class to represent a BankAccount


abstract class BankAccount {
// Data members of the BankAccount
String name;
String accountNumber;
String address;
double balance;

// Constructor to initialize the BankAccount


public BankAccount(String name, String accountNumber, String address, double balance) {
this.name = name;
this.accountNumber = accountNumber;
this.address = address;
this.balance = balance;
}
public void display() {
System.out.println("Account Holder: " + name);
System.out.println("Account Number: " + accountNumber);
System.out.println("Address: " + address);
System.out.println("Balance: $" + balance);
}
}

class SavingsAccount extends BankAccount {


// Additional member for return on investment
double returnOnInvestment;

public SavingsAccount(String name, String accountNumber, String address, double balance,


double returnOnInvestment) {
super(name, accountNumber, address, balance);
this.returnOnInvestment = returnOnInvestment;
}

void deposit(double amount) {


if (amount > 0) {
balance += amount;
System.out.println("$" + amount + " deposited.");
} else {
System.out.println("Invalid deposit amount.");
}
}
Page 9 of 12
void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("$" + amount + " withdrawn.");
} else {
Account Holder: John Doe

OR
16b Create software for dept stores to maintain the following details like item no, item CO5 K4
description, (i)requested quantity, cost price, provide the options to update the stock. Calculate
the selling price(SP=CP *20%). Create an exception whenever the selling price of item
exceeds the given amount

// Custom exception class for when the selling price exceeds the threshold
class SellingPriceExceededException extends Exception {
public SellingPriceExceededException(String message) {
super(message);
}
}

class Item {
private int itemNo;
private String description;
private int requestedQuantity;
private double costPrice;
private double sellingPrice;

public Item(int itemNo, String description, int requestedQuantity, double costPrice) {


this.itemNo = itemNo;
this.description = description;
this.requestedQuantity = requestedQuantity;
this.costPrice = costPrice;
this.sellingPrice = calculateSellingPrice();
}

public double calculateSellingPrice() {


return costPrice * 1.20;
}

public void updateStock(int quantity) {


this.requestedQuantity += quantity;
}

public void displayDetails() {


System.out.println("Item No: " + itemNo);
System.out.println("Description: " + description);
System.out.println("Requested Quantity: " + requestedQuantity);
System.out.println("Cost Price (CP): $" + costPrice);
System.out.println("Selling Price (SP): $" + sellingPrice);
}

public void checkSellingPrice(double threshold) throws SellingPriceExceededException {


if (sellingPrice > threshold) {
throw new SellingPriceExceededException("Selling price exceeds the threshold of $" +
threshold);
}
}

// Getter for selling price


public double getSellingPrice() {
return sellingPrice;
}
}

// Store Management class to manage the store inventory


import java.util.Scanner;

Page 10 of 12
class StoreManagement {
private static final double SELLING_PRICE_THRESHOLD = 1000.00;

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Array to store the items


Item[] items = new Item[10];
int itemCount = 0;

while (true) {
// Menu
System.out.println("\nDepartment Store Management");
System.out.println("1. Add Item");
System.out.println("2. Update Stock");
System.out.println("3. Display Item Details");
System.out.println("4. Exit");
System.out.print("Choose an option: ");
int option = scanner.nextInt();

switch (option) {
case 1:
// Add Item
System.out.print("Enter item number: ");
int itemNo = scanner.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter item description: ");
String description = scanner.nextLine();
System.out.print("Enter requested quantity: ");
int requestedQuantity = scanner.nextInt();
System.out.print("Enter cost price: ");
double costPrice = scanner.nextDouble();

items[itemCount] = new Item(itemNo, description, requestedQuantity, costPrice);


itemCount++;

// Check if the selling price exceeds threshold


try {
items[itemCount - 1].checkSellingPrice(SELLING_PRICE_THRESHOLD);
} catch (SellingPriceExceededException e) {
System.out.println(e.getMessage());
}

System.out.println("Item added successfully.");


break;

case 2:
// Update Stock
System.out.print("Enter item number to update: ");
int updateItemNo = scanner.nextInt();

boolean itemFound = false;


for (int i = 0; i < itemCount; i++) {
if (items[i].itemNo == updateItemNo) {
System.out.print("Enter quantity to add to stock: ");
int quantityToAdd = scanner.nextInt();
items[i].updateStock(quantityToAdd);
System.out.println("Stock updated successfully.");
itemFound = true;
break;
}
}
if (!itemFound) {
System.out.println("Item not found.");
}
break;

case 3:
Page 11 of 12
// Display Item Details
System.out.print("Enter item number to display: ");
int displayItemNo = scanner.nextInt();

itemFound = false;
for (int i = 0; i < itemCount; i++) {
if (items[i].itemNo == displayItemNo) {
items[i].displayDetails();
itemFound = true;
break;
}
}
if (!itemFound) {
System.out.println("Item not found.");
}
break;

case 4:
// Exit
System.out.println("Exiting the system.");
scanner.close();
return;

default:
System.out.println("Invalid option. Please try again.");
}
}
}
}

Course Faculty
R.UMA HOD
Dr.P.SUBHARAJAM
(Name /Sign / Date) (Name /Sign / Date)

Page 12 of 12

You might also like