OOP Java - IMP M 5
OOP Java - IMP M 5
rd
3 SEM Exam – Important Questions
MODULE – 5
1. Definition: Enumerations (enums) in Java are special data types used to define a collection of
constants. They provide a way to represent a fixed set of predefined values.
2. Purpose: Enumerations improve code readability, maintainability, and type safety by defining a set
of named constants that can be used throughout the codebase.
3. Declaration: Enums are declared using the enum keyword followed by the name of the
enumeration and a list of constant values enclosed in braces {}.
4. Example: Below is an example of an enumeration named DayOfWeek, representing the days of the
week.
In this example:
We define an enumeration named DayOfWeek containing seven constants representing each day of
the week.
In the main method, we create variables day1 and day2 of type DayOfWeek and assign them
constants MONDAY and WEDNESDAY, respectively.
We then print the values of day1 and day2, which will output "Day 1: MONDAY" and "Day 2:
WEDNESDAY" to the console.
(or)
2. Discuss values() and value Of() methods in Enumerations with suitable examples.
Ans:
values() and valueOf() Methods in Enumerations:
1. values() Method:
The values() method returns an array containing all the constants defined within an
enumeration.
It allows iterating over all the constants in the enumeration or accessing them by index.
This method is useful for tasks such as iterating through all enum constants or performing
operations on each constant.
2. valueOf() Method:
The valueOf() method is used to obtain the enum constant corresponding to the specified
string representation.
It parses the string and returns the enum constant with the matching name.
This method is helpful when converting user input or configuration settings represented as
strings into enum constants.
Example:
In this example:
We use the values() method to obtain an array of all constants in the DayOfWeek enumeration
and print them.
We then use the valueOf() method to obtain the enum constant representing Wednesday
("WEDNESDAY") and print it.
3. "Enumerations in Java are class types"-justify this statement with appropriate
examples.
Ans:
The statement "Enumerations in Java are class types" implies that enum types are treated as classes
in Java, offering features and capabilities similar to traditional classes. Here's how we can justify this
statement with appropriate examples:
In summary, the statement "Enumerations in Java are class types" is justified by the fact that enum
types are defined similarly to classes, can encapsulate behavior and state, and offer features
analogous to class types in Java.
(or)
4. Write a note on ordinal() and compare To() methods.
Ans:
ordinal() Method:
1. Explanation:
The ordinal() method returns the ordinal position of an enum constant within its
enumeration declaration.
Enum constants are assigned ordinal values starting from zero for the first constant,
incrementing by one for each subsequent constant.
This method provides a convenient way to obtain the numerical order of enum constants.
In this example, the ordinal() method is used to retrieve the ordinal position of the TUESDAY
constant, which is 2.
compareTo() Method:
1. Explanation:
The compareTo() method compares two enum constants based on their ordinal values.
It returns a negative integer if the invoking constant is less than the argument constant, zero
if they are equal, and a positive integer if the invoking constant is greater.
This method enables sorting enum constants in their natural order based on their ordinal
values.
2. Example:
In this example, the compareTo() method is used to compare MONDAY with WEDNESDAY, indicating that
MONDAY comes before WEDNESDAY. In this example, the compareTo() method is used to compare MONDAY
with WEDNESDAY, indicating that MONDAY comes before WEDNESDAY.
5. What are wrapper classes? Explain with examples.
Ans:
Wrapper Classes in Java:
1. Explanation:
Wrapper classes in Java are used to convert primitive data types into objects (i.e., to wrap
primitives into objects).
They provide a way to represent primitive data types as objects, allowing them to be used in
Java collections, generics, and other scenarios where objects are required.
Each primitive data type has a corresponding wrapper class in Java.
2. Example:
3. Output
4. Explanation (Continued):
In the example, we have primitive data types int and double.
We use the wrapper classes Integer and Double to wrap these primitive data types into
objects.
The valueOf() method is used to convert primitive data types to their corresponding
wrapper objects.
The resulting wrapper objects ( Integer and Double ) can then be used like any other objects
in Java.
5. Wrapper Classes in Java:
Byte, Short, Integer, Long: For representing integral values.
Float, Double: For representing floating-point values.
Character: For representing characters.
Boolean: For representing boolean values.
6. Usage:
Wrapper classes are commonly used in scenarios where primitive data types need to be
treated as objects, such as when working with collections like ArrayList, HashMap, or when
using generics.
Wrapper classes provide a convenient way to work with primitive data types in Java, allowing them
to be treated as objects and enabling additional functionalities such as methods and compatibility
with object-oriented features of Java.
6. Explain auto boxing /unboxing in expressions.
Ans:
Auto Boxing and Unboxing in Java:
1. Auto Boxing:
Auto boxing is the automatic conversion of primitive data types into their corresponding
wrapper classes when necessary.
It allows primitive data types to be used as objects without explicitly creating instances of
wrapper classes.
2. Example of Auto Boxing:
Auto boxing and unboxing simplify the process of working with primitive data types and wrapper
classes in Java, enhancing code readability and reducing boilerplate code.
4.Explanation (Program):
In the program, we define a class MyThread that extends the Thread class and overrides the
run() method.
Inside the run() method, each thread prints a message indicating its ID using
Thread.currentThread().getId().
In the main() method, we create and start multiple instances of MyThread to create multiple
threads.
Each thread executes concurrently, and their IDs are printed sequentially.
5.Usage:
Multithreading is used in scenarios where tasks can be performed concurrently, such as in
server applications, GUI programming, simulations, etc.
It helps improve program performance by utilizing available CPU resources more efficiently
and increasing responsiveness in applications.
1. Definition:
A thread in Java represents a separate path of execution within a program.
Threads allow for concurrent execution, enabling programs to perform multiple tasks
simultaneously.
2. Creating Threads:
Java provides two main approaches for creating threads:
Implementing the Runnable interface.
Extending the Thread class.
1. Explanation:
Define a class that implements the Runnable interface.
Implement the run() method to define the thread's behavior.
2. Example:
Extending the Thread Class:
1. Explanation:
Create a subclass that extends the Thread class.
Override the run() method to specify the thread's behavior.
2. Example:
(or)
Implementing Runnable:
Extending Thread:
These simplified points encapsulate the essence of creating threads in Java using both
approaches. They provide a concise understanding suitable for exam preparations.
9. Write a JAVA program to create two threads, one displays "computer science" and
another displays "information science" five times.
Ans:
In this program:
We define a MessageThread class that extends Thread.
Each MessageThread object is initialized with a specific message.
The run() method of MessageThread is overridden to display the message five times, with a 1-
second pause between each display.
In the main() method, we create two MessageThread objects with different messages and start
both threads using the start() method.
In this example, isAlive() is used to check if a thread is alive after starting it.
Explanation of join() Method:
2. join() Method:
join() is a method in Java that allows one thread to wait for the completion of another
thread.
When a thread calls join() on another thread, it waits until the specified thread terminates.
It is useful for coordinating the execution of multiple threads.
In this example, join() is used to wait for the completion of a thread's execution after starting it.
11. What is the need of synchronization? Explain with an example how synchronization is
implemented in JAVA.
Ans:
Need for Synchronization:
We have a Counter class with synchronized methods to increment the count and retrieve the
current count value.
Multiple threads are created to concurrently increment the counter.
Synchronization ensures that only one thread can access the increment() and getCount()
methods at a time, preventing race conditions.
As a result, the final count printed is the correct sum of increments performed by both threads.
(or)
12. Explain with an example how inter thread communication is implemented in JAVA
Ans:
Inter Thread Communication in Java:
Inter thread communication enables threads to synchronize and coordinate their execution in Java.
It's facilitated through methods like wait(), notify(), and notifyAll() from the Object class.
wait(): Pauses the current thread until another thread invokes notify() or notifyAll() for the
same object. Releases the object's lock during the wait.
notify(): Wakes up a single waiting thread on the object. If multiple threads are waiting, one is
chosen arbitrarily.
notifyAll(): Wakes up all threads waiting on the object. Allows them to compete for the lock.
These methods are used with synchronized blocks or methods to ensure proper synchronization
between threads, facilitating communication and coordination.
In this example, we have a Customer class with withdraw() and deposit() methods, which
are synchronized to ensure thread safety.
The withdraw() method checks if the balance is sufficient for withdrawal. If not, it waits for the
deposit() method to deposit funds.
The deposit() method adds funds to the balance and notifies the waiting thread that the deposit
is completed.
In the Test class, two threads are created: one for withdrawal and one for deposit.
The withdrawal thread attempts to withdraw an amount greater than the balance, so it waits for the
deposit thread to add funds.
After the deposit is completed, the withdrawal thread resumes and completes the withdrawal
process.
13. What is meant by thread priority? How to assign and get the thread priority?
Ans:
Thread Priority in Java:
Thread priority determines the preference given to a thread for CPU time when multiple threads are
competing. Thread priorities are represented by integers ranging from 1 to 10, where 1 is the
lowest priority and 10 is the highest. By default, threads inherit the priority of their parent thread.
Assigning Priority: You can set the priority of a thread using the setPriority(int priority)
method, where priority is an integer value between 1 and 10. Higher values indicate higher
priority.
Getting Priority: The priority of a thread can be obtained using the getPriority() method.
It's important to note that thread priority is merely a hint to the scheduler and does not guarantee
the execution order. The final decision lies with the JVM and underlying operating system
scheduler.
(or)
(or)
14. Explain how to achieve suspending, resuming and stopping threads with an example
program.
Ans:
Suspending, Resuming, and Stopping Threads in Java:
1. Suspending Threads:
Suspending a thread temporarily halts its execution without terminating it.
You can suspend a thread using the suspend() method.
2. Resuming Threads:
Resuming a suspended thread allows it to continue its execution.
Resuming is achieved using the resume() method.
3. Stopping Threads:
Stopping a thread terminates its execution.
It's recommended to use a flag or condition to control the termination of threads rather
than abruptly stopping them, as stopping threads abruptly can lead to resource leaks or
inconsistent program state.
You can implement stopping by setting a flag and checking it periodically in the thread's
execution loop.
(or)
Example Program:
This program demonstrates suspending, resuming, and stopping a thread using the
suspendThread(), resumeThread(), and stopThread() methods, respectively.
15. Explain Deadlock ?
Ans:
Deadlock is a situation in multithreading where two or more threads are blocked forever, waiting
for each other to release resources. This situation arises when two or more threads wait for
resources that are held by each other, resulting in a cyclic dependency and none of the threads
being able to proceed.
1. Deadlock occurs when two or more threads are waiting indefinitely for resources held by each
other.
2. Each thread waits for the other thread to release a resource before it releases its own resource,
leading to a stalemate situation.
Example: Consider two threads, Thread A and Thread B, each requiring two resources to complete
their task. If Thread A holds Resource 1 and requests Resource 2, while Thread B holds Resource 2
and requests Resource 1, a deadlock can occur:
In this scenario, both threads are waiting for the other to release the resource it holds, resulting in a deadlock
situation where neither thread can progress further.