SaranathanCollege of Engineering
(Autonomous)
Tiruchirappalli-12
Date/
Internal Assessment– II 28/10/2022 F.N Marks 50
Session
Course code CS3391 Course Title Object Oriented Programming.
Batch No. 23-27 Duration 90 mins Academic Year 2024-2025
Year II Semester/ Section III /A/B Department CSBS/CSE/AIML/IT
Part – A(Answer all the questions 10 x 2 = 20marks)
Q. No. Questions CO Skills
Distinguish between Abstract class and Interface. Can an Abstract class be C204.2 Az
declared as final?. Why?
Aspect Abstract Class Interface
Declared using
Keyword Declared using interface
abstract
Methods are abstract by
Can have abstract
default (before Java 8).
and concrete
Methods From Java 8 onwards, can
(implemented)
have default and static
1 methods
methods with body
All variables are
Can have instance and implicitly public
Variables
static variables static final
(constants)
A class can
A class can extend only one
Inheritanc implement multiple
abstract class (single
e interfaces (multiple
inheritance)
inheritance)
1. What is wrong with the following interface? C204.2 C
2. public interface SomethingIsWrong {
3. void aMethod(int aValue){
4. [Link]("Hi Mom");
}} Correct the error and rewrite the code.
· In an interface, methods cannot have a body (except for default and
static methods from Java 8 onwards).
2
· · Here, aMethod() is neither default nor static.
· public interface SomethingIsWrong {
default void aMethod(int aValue) {
[Link]("Hi Mom");
}
}
3 What is a package? Why should we use package. How will create a package C204.2 R
in java. How to import a package?
Package: A package in Java is a collection of related classes and interfaces
organized together.
Why use package?
Avoids name conflicts
Provides modularity
Easier to maintain large projects
Provides access protection
Allows reusability
How to create a package?
package mypack;
public class MyClass {
public void display() {
[Link]("Hello from package!");
}
}
How to import a package?
import [Link];
public class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link]();
}
}
Define Exception. What happens if an exception is not caught? C204.3 R
· Exception: An exception is an unwanted event that occurs during
4 program execution which disrupts normal flow.
· · If an exception is not caught, the JVM handles it, prints an error
message and terminates the program abnormally.
5. Differentiate ‘throws’ and ‘throw’ in java C204.3 Az
throw throws
Used to explicitly Declares exceptions a method may
throw an exception throw
Used inside
Used in method declaration
method body
5 Only one
Can declare multiple exceptions
exception at a time
Example: throw
new Example: void read() throws
IOException("Error! IOException, SQLException
");
6.
Create the Java code that should be executed at all times even if an exception C204.3 C
occurs?
try {
int x = 10 / 0;
6 } catch (Exception e) {
[Link]("Exception: " + e);
} finally {
[Link]("This block always executes");
}
7 How will you create a thread in java? C204.4 R
Extending Thread class
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
}
}
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
[Link]();
}
}
Thread is a lightweight process - Justify C204.4 Az
A thread shares the same memory, code, and resources of the process
but executes independently.
8
Unlike processes, threads do not require separate memory allocation
→ hence, lightweight.
Differentiate between start() and run() methods of thread C204.4 R
start() run()
Just executes run() like a
Creates a new thread and
normal method in the same
calls run() internally
9 thread
Executes in parallel Executes in single thread
(multithreading) (no concurrency)
Must be called once per Can be called multiple times
thread like a method
In what state a thread will be when a thread is created but not started? C204.4 A
10 When a thread is created using new Thread(), but before calling start(), it is in
the NEW state
Part – B(Answer all the questions 2 x 10 = 20marks) Maximum 2 splits/Question
Q. No. Questions CO Skills
1 Define Dynamic Method Dispatch? What is the use of Dynamic method C204.2 R
11 [Link] with an example.
Dynamic Method Dispatch (also called Runtime Polymorphism) is
the mechanism by which a call to an overridden method is resolved
at runtime rather than at compile-time
It is used when a superclass reference variable refers to a subclass
object, and the method that gets executed is the subclass’s overridden
version.
Achieves runtime polymorphism in Java.
Helps write flexible and reusable code.
Allows Java to support the “program to an interface, not an
implementation” principle.
Makes it possible to call methods on objects without knowing their
exact type at compile-time.
// Superclassclass Animal {
void sound() {
[Link]("Animal makes a sound");
}
}
// Subclass 1class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
// Subclass 2class Cat extends Animal {
@Override
void sound() {
[Link]("Cat meows");
}
}
// Main classpublic class Main {
public static void main(String[] args) {
// Superclass reference but object is of Dog
Animal a = new Dog();
[Link](); // Output: Dog barks
// Superclass reference but object is of Cat
a = new Cat();
[Link](); // Output: Cat meows
}
}
Reference type = Animal (superclass).
Object type = Dog or Cat (subclass).
At runtime, JVM looks at the actual object’s type (Dog or Cat) and
executes the corresponding sound() method.
This is Dynamic Method Dispatch.
Or
1 i. .Explain the concept of nested class with a simple example C204.2 U
12
Concept of Nested Class
A nested class is a class that is defined inside another class.
It is used to logically group classes that are only used in one place,
increase encapsulation, and make code more readable.
Types of Nested Classes in Java
Non-static nested class (Inner class)
Static nested class
Local class (defined inside a method)
Anonymous inner class
class Outer {
private String message = "Hello from Outer class";
// Inner class (non-static nested class)
class Inner {
void display() {
[Link](message); // Can access outer
class members
}
}
}
public class Main {
public static void main(String[] args) {
Outer outer = new Outer(); // Create outer object
[Link] inner = [Link] Inner(); // Create inner
object
[Link](); // Output: Hello from Outer class
}
}
👉 Here:Inner class is inside Outer [Link] class can directly access
Outer class members (even private ones).
ii. How Multiple Inheritance is possible in
Java?
Java does not support multiple inheritance with classes (to avoid
ambiguity, known as the Diamond Problem).
But Java supports multiple inheritance through interfaces.
A class can implement multiple interfaces, thus achieving multiple
inheritance.
ii. How Multiple inheritance is possible in java? Give a simple example code
// First interfaceinterface InterfaceA {
void methodA();
}
// Second interfaceinterface InterfaceB {
void methodB();
}
// Class implementing both interfacesclass MyClass
implements InterfaceA, InterfaceB {
public void methodA() {
[Link]("Method A from InterfaceA");
}
public void methodB() {
[Link]("Method B from InterfaceB");
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
[Link](); // Output: Method A from InterfaceA
[Link](); // Output: Method B from InterfaceB
}
}
1 Explain the thread life cycles with suitable examples. How will you set the C204.4 U
13 priority for a thread
Thread Life Cycle in Java
A thread in Java goes through several states during its life cycle, as defined
in [Link] enum:
1.
NEW
2.
1.
A thread object is created using new Thread(), but start() is
not yet called.
2.
3.
State: NEW.
4.
3.
RUNNABLE
4.
1.
After calling start(), the thread is ready to run but waiting for
CPU scheduling.
2.
3.
State: RUNNABLE.
4.
5.
RUNNING
6.
1.
When the CPU scheduler picks a thread, it enters the
RUNNING state and executes run().
2.
7.
WAITING
8.
1.
A thread is waiting indefinitely for another thread to signal
(notify()/notifyAll()).
2.
9.
TIMED_WAITING
10.
1.
A thread is waiting for a specific amount of time (sleep(ms),
join(ms), wait(ms)).
2.
11.
TERMINATED (DEAD)
12.
1.
Once run() finishes, the thread enters the TERMINATED
state.
2.
Diagram (simplified)
NEW --> RUNNABLE --> RUNNING -->
WAITING/TIMED_WAITING --> RUNNABLE -->
TERMINATED
Example of Thread Life Cycle
class MyThread extends Thread {
public void run() {
[Link]("Thread is running...");
try {
[Link](2000); // TIMED_WAITING
[Link]("Thread woke up after sleep");
} catch (InterruptedException e) {
[Link]("Thread interrupted");
}
}
}
public class Main {
public static void main(String[] args) throws
InterruptedException {
MyThread t = new MyThread();
[Link]("State before start: " + [Link]());
// NEW
[Link]();
[Link]("State after start: " + [Link]()); //
RUNNABLE
[Link](500); // Main sleeps so child gets CPU
[Link]("State while sleeping: " +
[Link]()); // TIMED_WAITING or RUNNABLE
[Link](); // Waits for thread t to finish
[Link]("State after completion: " +
[Link]()); // TERMINATED
}
}
Setting Thread Priority
Each thread has a priority (integer value between 1 and 10).
Constants:
Thread.MIN_PRIORITY = 1
o
o
Thread.NORM_PRIORITY = 5 (default)
o
o
Thread.MAX_PRIORITY = 10
Scheduler may use priority to decide which thread to run first (depends
on JVM & OS).
Example: Setting Priority
class MyThread extends Thread {
MyThread(String name) {
super(name);
}
public void run() {
[Link](getName() + " running with priority "
+ getPriority());
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread("Thread-1");
MyThread t2 = new MyThread("Thread-2");
MyThread t3 = new MyThread("Thread-3");
// Setting priorities
[Link](Thread.MIN_PRIORITY); // 1
[Link](Thread.NORM_PRIORITY); // 5
[Link](Thread.MAX_PRIORITY); // 10
[Link]();
[Link]();
[Link]();
}
}
Or
14 Two threads A and B are created will run for 10 units of time. Thread B will C204.4 C
run two times faster as thread A. Develop a java program to demonstrate this.
Let’s write a Java program to demonstrate two threads A and B where:
Both run for 10 time units.
Thread B runs twice as fast as Thread A → meaning it completes the
same work in half the time.
We can simulate "time units" using [Link]() where:
Thread A sleeps for 1000 ms per unit.
Thread B sleeps for 500 ms per unit (so it is 2x faster).
class ThreadA extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
[Link]("Thread A: Time unit " + i);
try {
[Link](1000); // 1 second per unit
} catch (InterruptedException e) {
[Link]("Thread A interrupted");
}
}
[Link]("Thread A finished");
}
}
class ThreadB extends Thread {
public void run() {
for (int i = 1; i <= 10; i++) {
[Link]("Thread B: Time unit " + i);
try {
[Link](500); // 0.5 second per unit (2x faster)
} catch (InterruptedException e) {
[Link]("Thread B interrupted");
}
}
[Link]("Thread B finished");
}
}
public class Main {
public static void main(String[] args) {
ThreadA a = new ThreadA();
ThreadB b = new ThreadB();
[Link](); // Start Thread A
[Link](); // Start Thread B
}
}
Both threads run 10 iterations (10 units).
Thread A → Sleeps 1000 ms each loop → 10 seconds total.
Thread B → Sleeps 500 ms each loop → 5 seconds total.
So, Thread B completes the task twice as fast as Thread A.
Part – C(Answer all the questions 1 x 10 = 10marks) Case study or Analytical type
Q. No. Questions CO Skills
1 Create a custom exception to handle runtime error in your code C204.3 C
15
In Java, you can create a custom exception by extending the Exception
(checked exception) or RuntimeException (unchecked exception) class.
Since you asked to handle a runtime error, we’ll extend
RuntimeException.
Here’s a simple example:
// Custom Exception Classclass MyCustomException extends
RuntimeException {
public MyCustomException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
public static void main(String[] args) {
try {
int num = -5;
// Throw custom exception if condition fails
if (num < 0) {
throw new MyCustomException("Number cannot
be negative!");
}
[Link]("Number is: " + num);
} catch (MyCustomException e) {
[Link]("Caught Custom Exception: " +
[Link]());
}
[Link]("Program continues after handling
exception...");
}
}
MyCustomException extends RuntimeException, making it an
unchecked exception.
In the main method, if the number is negative, the exception is
thrown.
The catch block handles the exception gracefully, preventing the
program from crashing.
Execution continues after handling the error.
Or
1 The value 100/0 is to be stored in the seventh position of an array of size 5. C204.3 AZ
16 Create a suitable error handling code for this requirement
Here we have two errors that may occur:
ArithmeticException – dividing 100/0.
ArrayIndexOutOfBoundsException – storing result in the 7th
position of an array of size 5.
We can write a try-catch block to handle both exceptions properly:
public class ErrorHandlingDemo {
public static void main(String[] args) {
int[] arr = new int[5]; // array of size 5
try {
// Risky operation: division by zero
int value = 100 / 0;
// Risky operation: storing at 7th position (index 6)
arr[6] = value;
[Link]("Value stored successfully!");
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero!");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Error: Trying to access an
invalid array index!");
} finally {
[Link]("Execution of try-catch block
completed.");
}
}
}
Error: Cannot divide by zero!
Execution of try-catch block completed.
✅ If you change division to 100/5, then the array index error will be
caught instead.
Bloom’s Skills: Remember (R), Understand (U), Apply (A), Analyze (AZ), Evaluate (E) and Create (C).
C204.2 -16 ; C204.3-16; C204.4-18