0% found this document useful (0 votes)
57 views30 pages

OOP Java - IMP M 5

Uploaded by

sunilgowda88849
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)
57 views30 pages

OOP Java - IMP M 5

Uploaded by

sunilgowda88849
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/ 30

OOPs in JAVA

rd
3 SEM Exam – Important Questions

MODULE – 5

1. Define Enumerations. Give an example.


Ans:
Enumerations:

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:

1. Defining Enumerations as Class Types:


 Enumerations in Java are defined using the enum keyword, which signifies the creation of a
new data type, similar to class declaration syntax.
 Enumerations can have constructors, methods, and fields, similar to classes. This allows
enum types to encapsulate behavior and state within themselves.
2. Example Demonstrating Enum as a Class Type:
3. Justification:
 In the above example, DayOfWeek is an enum type, defined using the enum keyword.
 It contains a constructor ( DayOfWeek()) and a method (getAbbreviation() ), demonstrating
behavior encapsulation similar to class types.
 Enum constants (SUNDAY , MONDAY, etc.) act as instances of the DayOfWeek enum type,
analogous to objects of a class.
 The enum constants can access methods and fields defined within the enum type, just like
objects accessing methods and fields of a class instance.
4. Usage Similarity with Class Types:
 Enumerations are used to represent a fixed set of predefined constants, providing type
safety and readability.
 They can be used in switch statements, method parameters, and return types, just like class
types.
 Enumerations support inheritance, interfaces, and annotations, further emphasizing their
class-like behavior and capabilities.

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:

3. Explanation (Auto Boxing):


 In the example, primitive data types ( int and double) are assigned directly to objects of
their corresponding wrapper classes (Integer and Double).
 Java automatically converts the primitive values into objects of the wrapper classes using
auto boxing.
4. Unboxing:
 Unboxing is the automatic conversion of wrapper class objects into their corresponding
primitive data types when necessary.
 It allows objects of wrapper classes to be used as primitive data types without explicitly
extracting their values.
5. Example of Unboxing:
6. Explanation (Unboxing):
 In the example, objects of wrapper classes ( Integer and Double) are assigned directly to
primitive data types (int and double).
 Java automatically extracts the values from the wrapper class objects and assigns them to
the corresponding primitive data types using unboxing.
7. Usage:
 Auto boxing and unboxing provide syntactic sugar, making code more readable and concise
by eliminating the need for manual conversions between primitive data types and wrapper
classes.
 They are commonly used when working with collections, generics, and other scenarios
where primitive data types and objects need to interact seamlessly.

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.

7. What is multithreading? Write a program to create multiple threads in JAVA


Ans:
1. Explanation:
 Multithreading is the ability of a CPU or a single core in a computer to provide multiple
threads of execution concurrently.
 In Java, multithreading allows a program to perform multiple tasks simultaneously by
dividing its execution into multiple threads.
 Each thread represents a separate flow of execution within the same program.
2. Example Program - Creating Multiple Threads:
3. Output (Sample):

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.

Multithreading in Java allows programs to perform multiple tasks simultaneously, enhancing


performance and efficiency in various applications.
(or)
Output:
8. What do you mean by thread? Explain the different ways of creating threads.
Ans:
Thread in Java:

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.

Implementing the Runnable Interface:

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:

1. Definition: Runnable interface abstracts a unit of executable code.


2. run() Method: Implementing classes need to provide a run() method, which serves as the
entry point for the new thread.
3. Thread Instantiation: After implementing Runnable, instantiate a Thread object using the
constructor Thread(Runnable threadOb, String threadName).
4. Starting the Thread: Call the start() method on the Thread object to begin execution of
the new thread.
5. Execution Context: Code within run() operates like any other method, allowing for
method calls, variable declarations, etc.

Extending Thread:

1. Definition: Another way to create a thread is by extending the Thread class.


2. Override run(): The extending class must override the run() method to define the
thread's behavior.
3. Starting the Thread: Invoke start() method to commence execution of the thread.
4. run() Execution: Code within the overridden run() method specifies what the thread
should execute.
5. Simplicity: Extending Thread offers a straightforward approach, but limits the flexibility to
extend other classes.

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.

10. With syntax, explain use Of is Alive( ) and join( ) methods.


Ans:
1. isAlive() Method:
 isAlive() is a method in Java used to check whether a thread is alive or not.
 A thread is considered alive if it has been started and has not yet completed execution or
terminated.
 It returns a boolean value, true if the thread is alive, false otherwise.
Syntax of isAlive() Method:

Example of isAlive() 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.

Syntax of join() Method:

Example of join() Method:

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:

1. Ensuring Thread Safety:


 In a multithreaded environment, multiple threads may access shared resources concurrently,
leading to data inconsistency and errors.
 Synchronization is needed to ensure that only one thread can access the shared resource at
any given time, thus preventing race conditions and maintaining data integrity.
2. Preventing Concurrent Access:
 Synchronization prevents multiple threads from accessing critical sections of code
simultaneously.
 It ensures that the state of shared objects remains consistent and prevents conflicts arising
from concurrent access.
Example of Synchronization in Java:
In this example:

 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.

Example of Inter Thread Communication in Java:


Output:
Explanation:

 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.

You might also like