PBCST 304 Object Oriented Programming Model Question Paper and Answers
java MyApp
on each machine, and it executes successfully. What is the name of the compiled file format that makes this possible?
When you compile a Java source file (MyApp.java
) using the Java compiler (javac
), it does not produce machine code specific to Windows, Linux, or macOS.
Instead, it produces platform-independent bytecode, which is stored in the file:
This file contains instructions for the Java Virtual Machine (JVM), not for any specific hardware or operating system
Why it runs everywhere
Each platform (Windows, Linux, macOS) has its own JVM implementation.
When you run:
The JVM on that platform reads and executes the same bytecode instructions — making Java platform-independent.
2.What will be the value of a after the execution of the following code segment in Java.
int a = -1;
a = a >> 4;
🧠 Step 1: Represent a = -1 in binary (32-bit signed integer)
In Java, int is 32 bits, and negative numbers are represented in two’s complement form.
-1 in binary (32 bits) is:
11111111 11111111 11111111 11111111
🧠 Step 2: Right shift by 4 bits → a >> 4
The operator >> is the arithmetic right shift operator.
It preserves the sign bit (the leftmost bit).
Since a is negative (sign bit = 1), the leftmost bits filled during the shift are all 1s.
So, shifting right by 4 bits:
11111111 11111111 11111111 11111111 (original)
>> 4
11111111 11111111 11111111 11111111 (after shifting)
Essentially, it stays the same — still all 1s.
🧮 Step 3: Result in decimal
11111111 11111111 11111111 11111111 = -1
✅ Final Answer:
a = -1;
3.You’re given this Java code:
class Vehicle {
protected String type = "Generic Vehicle";
Vehicle() {
System.out.println("Vehicle created");
}
}
class Car extends Vehicle {
protected String type = "Car";
Car() {
// **INSERT STATEMENT A HERE**
System.out.println("Type: " + type);
}
void printParentType() {
System.out.println("Parent Type: " +super.type);
}
}
public class TestSuper {
public static void main(String[] args) {
Car c = new Car();
c.printParentType();
}
}
a. What exact statement must replace // **INSERT STATEMENT A HERE** so that when you run TestSuper, you see:
Vehicle created
Type: Car
Parent Type: Generic Vehicle
b. In one sentence each, explain:
(i) What the statement you inserted does here.
(ii) Why super.type prints "Generic Vehicle" while type prints "Car".
The correct statement to insert
✅ Full corrected Car
constructor
What happens when executed
Output:
🅱️ Explanations
(i) What super();
does here
👉 It calls the constructor of the parent class (Vehicle
) before executing the body of the Car
constructor, ensuring that the parent class is properly initialized first.
(ii) Why super.type
prints "Generic Vehicle" while type
prints "Car"
👉 Because each class has its own type
field, and super.type
explicitly refers to the parent class variable in Vehicle
, while type
(without super
) refers to the child class variable in Car
.
✅ Final Answers:
Part | Answer |
---|---|
(a) | super(); |
(b)(i) | It calls the parent class constructor before executing the subclass constructor. |
(b)(ii) | super.type accesses the parent’s variable, while type accesses the child’s variable. |
Inheritance in Java is a mechanism where one class (called the subclass or child class) acquires the properties and behaviors (fields and methods) of another class (called the superclass or parent class).
It promotes code reusability and method overriding.
Example:
Output:
Vehicle starts Car drives
🧩 1. Definition
Feature | Abstract Class | Interface |
---|---|---|
Purpose | Used when classes share a common base with some shared implementation. | Used to define a contract that classes must follow. |
Keyword | abstract | interface |
🧠 2. Example of Abstract Class
Output:
✅ Key Point: Abstract classes can have both abstract and concrete methods.
⚙️ 3. Example of Interface
Output:
✅ Key Point: Interfaces contain only abstract methods (till Java 7), but from Java 8 onward, they can include default and static methods.
📘 4. Summary Table
Feature | Abstract Class | Interface |
---|---|---|
Methods | Can have abstract and concrete methods | Can have only abstract (and default/static) methods |
Variables | Can have instance variables | Variables are implicitly public static final (constants) |
Inheritance | Class can extend only one abstract class | Class can implement multiple interfaces |
Constructor | Can have constructors | Cannot have constructors |
Use Case | When classes share common behavior | When classes share common capabilities |
💡 In Short:
Use abstract class when you want to share code among related classes.
Use interface when you want to define a common contract for unrelated classes.
Line(s) | Exception Class | Type | Reason |
---|---|---|---|
7 | FileNotFoundException | Checked | File may not exist; compiler forces handling |
8 | IOException | Checked | Closing file may fail; compiler forces handling |
4 | ArithmeticException | Unchecked | Division by zero occurs at runtime |
11 | ArrayIndexOutOfBoundsException | Unchecked | Missing command-line argument at runtime |
12-13 | NumberFormatException | Unchecked | Invalid integer parsing; runtime error |
Feature | Checked Exception | Unchecked Exception |
---|---|---|
Definition | Exceptions checked by the compiler at compile-time. | Exceptions not checked by the compiler; occur at runtime. |
Handling | Must be handled using try-catch or declared using throws . | Handling is optional; compiler does not force it. |
Inheritance | Subclass of Exception (but not RuntimeException). | Subclass of RuntimeException . |
Examples | IOException , FileNotFoundException , SQLException | ArithmeticException , NullPointerException , ArrayIndexOutOfBoundsException |
When occurs | Often due to external factors beyond the program’s control (e.g., file I/O, network). | Often due to programming errors (e.g., division by zero, invalid array access). |
Compile-time vs Runtime | Detected at compile-time. | Detected at runtime. |
Key Points
-
Checked exceptions → Force you to write robust code for recoverable conditions.
-
Unchecked exceptions → Usually indicate bugs in the code that should be fixed.
Quick Memory Tip:
Checked → Compiler checks;
Unchecked → Unnoticed by compiler.
7.Give the differences between AWT and Swing in Java.
AWT: Heavyweight, platform-dependent GUI toolkit with basic components.
Swing: Lightweight, platform-independent GUI toolkit with rich, customizable components.
Here’s a concise table comparing AWT and Swing in Java:
Feature | AWT (Abstract Window Toolkit) | Swing |
---|---|---|
Library | Part of java.awt package | Part of javax.swing package |
Components | Heavyweight (depends on native OS GUI) | Lightweight (pure Java components) |
Look and Feel | Depends on OS | Consistent across platforms; supports pluggable look and feel |
Flexibility | Less flexible | More flexible and customizable |
Performance | Faster for simple apps | Slightly slower due to additional features |
Components Examples | Button , Label , TextField | JButton , JLabel , JTextField |
Event Handling | Uses older event delegation | Uses newer event delegation model |
Use Case | Simple GUI applications | Rich and complex GUI applications |
Main Steps to Establish a JDBC Connection
-
Load the JDBC Driver
-
Establish a Connection
-
Create a Statement or PreparedStatement
-
Execute SQL Queries
-
Process the ResultSet
-
Close Resources
2️⃣ PreparedStatement vs Statement
Feature | Statement | PreparedStatement |
---|---|---|
Definition | Used to execute static SQL queries | Used to execute parameterized SQL queries |
SQL Injection | Vulnerable to SQL injection | Prevents SQL injection |
Performance | Compiles query every time | Precompiled once; faster for repeated queries |
Parameter Binding | Not supported | Supports dynamic parameter binding using ? |
Example | stmt.executeUpdate("INSERT INTO student VALUES(1,'John')"); | pstmt.setInt(1,1); pstmt.setString(2,"John"); pstmt.executeUpdate(); |
✅ Key Points
-
Use PreparedStatement for security, efficiency, and reusability.
-
Use Statement only for simple, one-time SQL queries
If the user enters one argument, the program should treat it as the side of a square and print the area of the square.
If the user enters two arguments, the program should treat them as the length and breadth of a rectangle and print the area of the rectangle.
If the number of arguments is not 1 or 2, display an appropriate error message.
this
in Java?
-
this
is a reference variable in Java that refers to the current object of a class. -
It is commonly used to:
-
Refer to instance variables when local variables shadow them.
-
Invoke the current class constructor (constructor chaining).
-
Pass the current object as a parameter to methods or constructors.
-
2️⃣ Examples
(a) Using this
to refer to instance variables
Output:
✅ Explanation: this.name
differentiates the instance variable name
from the constructor parameter name
.
(b) Using this()
to call another constructor
Output:
✅ Explanation: this()
is used to reuse another constructor in the same class.
(c) Using this
to pass current object
Output:
✅ Explanation: this
is used to pass the current object to another method or class.
3️⃣ Key Points
-
this
always refers to the current object. -
Helps resolve name conflicts between instance variables and parameters.
-
Can be used for constructor chaining (
this()
). -
Can be used to pass the current object as an argument.
1️⃣ Principle Applied
SOLID Principle: Single Responsibility Principle (SRP)
A class should have only one reason to change.
Why:
-
The original
Book
class handled data storage, validation, and display all in one class. -
Refactoring separates concerns:
-
Book → stores book data only.
-
BookValidator → validates book data.
-
BookPrinter → handles display/output.
-
2️⃣ Refactored Code
Book.java (Data class only)
BookValidator.java (Validation responsibility)
BookPrinter.java (Display/Output responsibility)
TestBook.java (Main method)
3️⃣ Benefits
-
Single Responsibility: Each class has one reason to change.
-
Maintainable: Validation rules or display formats can change independently.
-
Reusable:
BookPrinter
andBookValidator
can be reused in other projects.
- Same method name but different parameter lists (number or type of parameters).
- Return type can be different but is not sufficient alone to overload a method.
- Compile-time polymorphism is achieved using method overloading.
Key Points
- Static variable (count) is shared by all objects of the class.
- Incrementing count in the constructor ensures every new object is counted.
- Can access the static variable using ClassName.variableName (Counter.count).
Key Points
- Method overriding occurs when a subclass provides a specific implementation of a method defined in the parent class.
- Runtime polymorphism: The method that gets executed is determined at runtime based on the actual object, not the reference type.
- The @Override annotation is optional but recommended for clarity and compile-time checking.
1️⃣ Logger Interface
2️⃣ Third-Party AnalyticsService
3️⃣ Adapter Class
4️⃣ Demo / Main Class
Sample Output:
✅ Key Points
-
Adapter Design Pattern: Converts one interface (
AnalyticsService
) to another (Logger
) that the client expects. -
AnalyticsLoggerAdapter
implements the target interface (Logger
) and internally uses the adaptee (AnalyticsService
). -
This allows your code to work with the third-party class without modifying it.
1️⃣ Logger Singleton Class
2️⃣ Main Class to Test Logger
Explanation of Singleton Mechanism
-
Private static variable:
private static Logger instance;
ensures only one instance can exist. -
Private constructor:
private Logger()
prevents creating instances from outside the class. -
Public static method:
getInstance()
provides controlled access to the single instance.-
If the instance doesn’t exist, it is created.
-
If it already exists, the same instance is returned.
-
-
Ensures single instance:
-
logger1
andlogger2
point to the same object, guaranteeing only one logger writes to the file.
-
Sample Output:
Both references are the same instance!Application started
Features Implemented
-
Swing GUI
-
Text field for entering name.
-
Buttons:
Greet
,Clear
,Save
. -
Label to display greeting messages.
-
-
Event Handling
-
Implements
ActionListener
. -
Uses
addActionListener()
to register buttons. -
Handles click events inside
actionPerformed()
.
-
-
JDBC Integration
-
Connects to MySQL database (
testdb
). -
Uses PreparedStatement to safely insert name into
greetings
table. -
Handles exceptions using try-catch and displays messages via
JOptionPane
.
Explanation
-
View (GreetingApp)
-
Swing components: text field, label, buttons.
-
Displays messages and gets user input.
-
-
Controller (actionPerformed)
-
Handles button clicks.
-
Validates input.
-
Calls the Model to save data or update the View.
-
-
Model (Database / JDBC)
-
Manages data storage and retrieval.
-
Uses JDBC to insert names into the
greetings
table.
-
✅ Key Idea:
-
View → displays interface
-
Controller → handles events / logic
-
Model → manages data
This structure separates GUI, logic, and data, following the MVC design pattern
16b.Describe how you’d apply Dependency Inversion so the Controller can be unit-tested without a real database.
Making the Controller Testable with Dependency Inversion
Problem:
Right now, the Controller talks directly to the database.
-
This makes testing hard because you need a real database.
Solution:
-
Make the Controller talk to an interface instead of the real database.
-
This way, we can give it a fake database (mock) during testing.
Step 1: Create an interface
Step 2: Make the real database implement it
Step 3: Controller depends on the interface
Step 4: Use a mock repository for testing
Key Idea (Simple Version)
-
Controller doesn’t care about the database—it only talks to
GreetingRepository
. -
For testing, we replace the real database with a fake one.
-
This is Dependency Inversion: depend on abstraction, not concrete classes.
Comments
Post a Comment