0% found this document useful (0 votes)
9 views

JAVA QB SOL(MODULE 2-3)

Uploaded by

Anugala Aniketh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

JAVA QB SOL(MODULE 2-3)

Uploaded by

Anugala Aniketh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

MODULE-02

1.Define Inheritance. Explain the types of Inheritance with suitable examples.

Ans:

Inheritance is a mechanism in which one class acquires the property of another class

Types of Inheritance are

I. Single Inheritance
II. Mul ple Inheritance
III. Mul level Inheritance
IV. Hierarchial Inheritance
V. Hybrid Inheritance
 Single Inheritance: A subclass inherits from a single superclass. Java supports single inheritance
for classes.
Ex:
class Animal {
void eat() {
System.out.println("Animal is ea ng.");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog is barking.");
}
}
 Mul ple Inheritance (Through Interfaces): While Java does not support mul ple
inheritance for classes (where a class directly inherits from mul ple classes), it does
support mul ple inheritance through interfaces. An interface can be implemented by
mul ple classes, allowing them to share method signatures.
Ex:
interface Swimmer {
void swim();
}

interface Walker {
void walk();
}

class Duck implements Swimmer, Walker {


public void swim() {
System.out.println("Duck is swimming.");
}

public void walk() {


System.out.println("Duck is walking.");
}
}

 Mul level Inheritance: In mul level inheritance, a derived class inherits from another
derived class, forming a chain of inheritance.
Ex:
class Vehicle {
void move() {
System.out.println("Vehicle is moving.");
}
}

class Car extends Vehicle {


void honk() {
System.out.println("Car is honking.");
}
}

class ElectricCar extends Car {


void charge() {
System.out.println("Electric car is charging.");
}
}
 Hierarchical Inheritance: In hierarchical inheritance, mul ple classes inherit from a single
superclass.
Ex:
class Shape {
void draw() {
System.out.println("Drawing a shape.");
}
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing a circle.");
}
}

class Square extends Shape {


void draw() {
System.out.println("Drawing a square.");
}
}
 Hybrid Inheritance: Hybrid inheritance is a combina on of any two or more types of
inheritance, like combining single and mul ple inheritance.
Ex:
class A {
void methodA() {
System.out.println("Method A");
}
}

class B extends A {
void methodB() {
System.out.println("Method B");
}
}

class C extends A {
void methodC() {
System.out.println("Method C");
}
}

class D extends B {
void methodD() {
System.out.println("Method D");
}
}
2. Explain Overloading and Overriding within the scope of Inheritance using a suitable example.
3. How overriding is different from overloading? Explain with an example. Or why overridden methods are
used in Java? Explain with an example.

Ans:

Overloading:
Overloading is a feature in Java that allows a class to have mul ple methods with the same
name but different parameter lists. Overloaded methods are differen ated by the number or type
of parameters they accept.
Ex:
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}

Overriding:
Overriding is a feature that allows a subclass to provide a specific implementa on for a
method that is already defined in its superclass. The method in the subclass should have the same
method signature (method name and parameter types) as the method in the superclass.
Ex:
class Shape {
void draw() {
System.out.println("Drawing a shape.");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle.");
}
}
Why Overridden Methods are Used:
Overridden methods are used to achieve polymorphism and dynamic method invoca on.
They allow a subclass to provide its own specialized implementa on of a method defined in its
superclass. This is par cularly useful in scenarios where you want to work with objects of different
subclasses in a uniform way.
Ex:
public class Main {
public sta c void main(String[] args) {
Animal dog = new Dog();
Animal cat = new Cat();

dog.makeSound(); // Output: Dog barks.


cat.makeSound(); // Output: Cat meows.
}
}
4. With an example, give the two uses of the super keyword.
Ans:

The super keyword in Java is used to refer to the immediate parent class of a subclass. It can be
used in two primary ways:

I. To Call Superclass Constructor:

The super() constructor call is used to invoke the constructor of the superclass. This is
useful when a subclass constructor needs to perform addi onal tasks or ini alize variables that
are specific to the subclass, while also making sure that the ini aliza on code from the superclass
constructor is executed.

Ex: class Parent {

Parent() {

System.out.println("Parent constructor");

class Child extends Parent {

Child() {

super(); // Calling the parent class constructor

System.out.println("Child constructor");

public class Main {

public sta c void main(String[] args) {

Child child = new Child();

OUTPUT
Parent constructor
Child constructor
II. To Call Superclass Method:
The super keyword can also be used to call a method of the superclass when a
subclass wants to provide its own implementa on but s ll needs to access the method of
the parent class.
Ex:
class Parent {
void display() {
System.out.println("Parent's display method");
}
}
class Child extends Parent {
@Override
void display() {
super.display(); // Calling the parent class method
System.out.println("Child's display method");
}
}
public class Main {
public sta c void main(String[] args) {
Child child = new Child();
child.display();
}
}

OUTPUT
Parent's display method
Child's display method
5. Write a short note on i) Super keyword ii) Final keyword iii) Dynamic method dispatch

Ans:

I. Super Keyword

Ans:

The super keyword in Java is used to refer to the immediate parent class of a subclass. It has two
primary uses:

 To call the constructor of the superclass using super() in the subclass constructor. This ensures that
the ini aliza on code of the superclass is executed before the subclass's own ini aliza on.
 To call methods or access fields from the parent class even when they are overridden in the
subclass. This is useful when you want to u lize or extend the func onality of the parent class
while adding specific behavior in the subclass.

Ex:

class Parent {

void display() {

System.out.println("Parent's display method");

class Child extends Parent {

@Override

void display() {

super.display(); // Calling the parent class method

System.out.println("Child's display method");

}
II. Final Keyword:

The final keyword in Java is used to denote that a class, method, or variable cannot be
further subclassed, overridden, or modified, respec vely.
 A final class cannot be extended, ensuring that its design remains unchanged.
 A final method cannot be overridden in its subclasses, preserving the behavior defined in
the parent class.
 A final variable cannot be reassigned a er its ini al value is set, providing immutability.

Ex:

final class FinalClass {

// This class cannot be extended.

class Parent {

final void display() {

// This method cannot be overridden in subclasses.

class Main {

final int value = 10; // This variable cannot be reassigned.

III. Dynamic Method Dispatch:

Dynamic method dispatch is a mechanism in Java where the method to be executed is


determined at run me, based on the actual type of the object rather than the reference type. This
is achieved through method overriding and polymorphism.

Example:

class Animal {

void makeSound() {

System.out.println("Animal makes a sound.");

class Dog extends Animal {

void makeSound() {
System.out.println("Dog barks.");

public class Main {

public sta c void main(String[] args) {

Animal animal = new Dog();

animal.makeSound(); // Output: Dog barks.

6. Demonstrate the working of the Abstract class with a suitable example.

Ans:

Abstraction is a process of hiding the implementation details and showing only


functionality to the user.

Ex:

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }
7. Define excep on? Explain Excep on types with examples.

Ans:

An excep on in Java is an event that occurs during the execu on of a program, disrup ng the
normal flow of instruc ons. Excep ons are used to handle run me errors or excep onal situa ons that
can't be resolved at compile me. Java provides a robust excep on handling mechanism to deal with such
situa ons, helping to write more reliable and resilient programs. Excep on handling involves iden fying,
capturing, and dealing with excep ons to prevent program crashes and to provide meaningful error
messages to users.

Types of Excep on are:

 Checked Excep on
 Unchecked Excep on(Run me Excep on)
 Error

I. Checked Expression

Checked excep ons are the excep ons that are checked at compile- me. Code that might raise
checked excep ons must be placed within a try-catch block or declared in the method signature
using the throws keyword.

Ex:

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.IOExcep on;

public class FileReadExample {

public sta c void main(String[] args) {

try {

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));

String line = reader.readLine();

System.out.println(line);

reader.close();

} catch (IOExcep on e) {

System.out.println("An error occurred: " + e.getMessage());

}
II. Unchecked Excep ons (Run meExcep ons):
Unchecked excep ons, also known as run me excep ons, do not need to be explicitly
caught or declared in the method signature. They occur at run me and typically indicate
programming errors, like dividing by zero or accessing an array index out of bounds.

Ex:

public class DivisionExample {

public sta c void main(String[] args) {

int a = 10, b = 0;

int result = a / b; // Arithme cExcep on: division by zero

System.out.println(result);

III. Error
Errors are excep onal condi ons that usually can't be handled by a Java program. They
indicate serious problems that are beyond the control of the applica on, like running out of
memory or hardware failures. Errors are not meant to be caught or handled; they are o en used
to indicate unrecoverable situa ons.

Ex:

public class OutOfMemoryExample {

public sta c void main(String[] args) {

int[] array = new int[Integer.MAX_VALUE]; // OutOfMemoryError

}
8. What is an exception? Give the keywords and the general structure of an exception-handling
block.
OR

Explain the following with suitable examples


i) try and catch block ii) multiple catch clauses iii) throw iv) throws v) inally
Ans:

i) Try and Catch Block:


the try and catch blocks are used for exception handling. The try block contains the code
that might raise an exception, and the catch block(s) handle the exceptions that are caught. Here's
an example in Java

try {
int result = 10 / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
ii) Multiple Catch Clauses:
When dealing with multiple types of exceptions that might occur within a try block, you can
use multiple catch clauses to handle each type of exception differently. Here's a Java example:
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // This will cause an ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bounds: " + e.getMessage());
} catch (Exception e) {
System.out.println("An error occurred: " + e.getMessage());
}
iii) Throw:
The throw keyword is used to manually raise an exception in your code. You can use it when
you encounter a situation that warrants an exceptional condition. Here's a Java example:
public void validateAge(int age) throws IllegalArgumentException {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative.");
}
System.out.println("Age is valid: " + age);
}

public static void main(String[] args) {


try {
validateAge(-5);
} catch (IllegalArgumentException e) {
System.out.println("Error: " + e.getMessage());
}
}

iv) Throws:
The throws keyword is used in method declarations to indicate that the method might throw
a speci ic type of exception. It's used to notify callers of the method that they need to handle the
potential exceptions. Here's a Java example:
public void readFile(String ilename) throws IOException {
// Code to read a ile
}

v) Finally:
The finally block is used to define a sec on of code that is guaranteed to be executed, regardless
of whether an excep on was thrown or not. It's o en used for resource cleanup.
9. Demonstrate the working of nested try blocks, with suitable examples and syntax.
Ans:

Nested try blocks are used when you have a try block within another try block. This structure
allows you to handle different levels of excep ons at various scopes

Syntax

try {

// Outer try block

// This code may throw excep ons

try {

// Inner try block

// This code may also throw excep ons

} catch (Excep onType1 innerExcep on1) {

// Inner catch block for Excep onType1

} catch (Excep onType2 innerExcep on2) {

// Inner catch block for Excep onType2

} finally {

// Inner finally block

} catch (Excep onType3 outerExcep on3) {

// Outer catch block for Excep onType3

} catch (Excep onType4 outerExcep on4) {

// Outer catch block for Excep onType4

} finally {

// Outer finally block

}
class Main {
// main method
public static void main(String args[]) {
try {
int a[] = {30, 45, 60, 75, 90, 105, 120, 140, 160, 200};
// displaying element at index 8
System.out.println("Element at index 8 = "+a[8]);
// another try block
try {
System.out.println("Division");
int res = 100/ 0;
}
catch (ArithmeticException ex2) {
System.out.println("Sorry! Division by zero isn't feasible!");
}
}
catch (ArrayIndexOutOfBoundsException ex1) {
System.out.println("ArrayIndexOutOfBoundsException");
}
}
}

Output
Element at index 8 = 160
Division
Sorry! Division by zero isn't feasible!
10. Demonstrate the use of a user-de ined exception class with a suitable example.
Ans:
User-de ined exception classes allow you to create custom exceptions that suit your
application's speci ic needs. To create a user-de ined exception, you need to create a new class
that extends an existing exception class (usually Exception or one of its subclasses). Here's an
example in Java:

// A Class that represents use-de ined exception

class MyException extends Exception {


public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}

// A Class that uses above MyException


public class Main {
// Driver Program
public static void main(String args[])
{
try {
// Throw an object of user de ined exception
throw new MyException("GeeksGeeks");
}
catch (MyException ex) {
System.out.println("Caught");

// Print the message from MyException object


System.out.println(ex.getMessage());
}
}
}

Output
Caught

GeeksGeeks
MODULE-03

1. What is a Package? What are the steps involved in creating user-defined Packages?
Ans:
 A java package is a group of similar types of classes, interfaces and sub-packages.
 Package in java can be categorized in two form, built-in package and user-defined package.
 Steps Involved in creating User defined Packages are
o Create Directory Structures
o Create Java Files
o Compile
o Use the Package
o Compile & Run

 Create Directory Structure: Packages are organized as directories within the source code
directory. The package name corresponds to the directory structure. For example, if you
want to create a package named com.mycompany.myapp, create the directory structure
as src/com/mycompany/myapp.
 Create Java Files: Inside the package directory, create Java source files with the desired
classes or functions. Each Java file should begin with a package declaration to indicate
which package it belongs to. For example:

package com.mycompany.myapp;
public class MyClass {
// class code here
}
 Compile: Compile the Java files using the command-line compiler or an integrated
development environment (IDE). You need to navigate to the root directory of your source
files and compile using the package structure. For example:

javac src/com/mycompany/myapp/MyClass.java

 Use the Package: In other parts of your code or in other projects, you can import and use
the classes from your created package. Import the package at the beginning of your Java
file using an import statement. For example:

import com.mycompany.myapp.MyClass;

public class AnotherClass {


public static void main(String[] args) {
MyClass myObject = new MyClass();
// use myObject
}
}
 Compile and Run: Compile and run the code that uses the package. The compiler will
automatically find the imported classes and resources from the specified package.
2. What are Access Specifiers? Explain with suitable examples.

Ans:

 Access specifiers, also known as access modifiers, are keywords in programming


languages like Java that define the visibility and accessibility of classes, methods, fields,
and other members within a class or package.
 They control which parts of a program can access or interact with certain components.
 In Java, there are four main access specifiers:
o Public
o Protected
o Default
o Private

I. Public: Members marked as public are accessible from anywhere, both within the same
class and from outside the class. There are no restrictions on accessing public members.

public class MyClass {

public int publicField;

public void publicMethod() {

// method code here

} }

II. Protected: Members marked as protected are accessible within the same class,
subclasses (even if they are in different packages), and within the same package. They
are not accessible from outside the package if they are not part of a subclass.

package com.mycompany.myapp;

public class MyBaseClass {


protected int protectedField;

protected void protectedMethod() {


// method code here
}
}
III. Default (no modifier): Members with no explicit access modifier (also known as
package-private) are accessible only within the same package. They are not accessible
from outside the package.

package com.mycompany.myapp;
class MyPackageClass {
int defaultField; // package-private
void defaultMethod() {
// method code here
}
}

IV. Private: Members marked as private are accessible only within the same class. They
are not accessible from subclasses, other classes within the same package, or from
outside the package.

public class MyClass {


private int privateField;

private void privateMethod() {


// method code here
}
}

3. Define an Interface? List the differences between an Interface and an Abstract Class with
syntax.

Ans:

An interface in Java is a blueprint of a class. It has static constants and abstract methods.
4. What is the alternative approach to implementing multiple inheritances in Java? Explain
with an example.
Ans:
 In Java, the alternative approach to achieving multiple inheritance is by using
interfaces. Interfaces allow a class to inherit multiple sets of method contracts without
introducing the complexities and ambiguities associated with multiple inheritance
through classes.
 In this approach, a class can implement multiple interfaces, each defining a set of
methods that the implementing class must provide. This allows a class to inherit
behavior from multiple sources while avoiding the complexities and ambiguities
associated with traditional multiple class inheritance.
Ex:
// Interface for flying behavior
interface Flying {
void fly();
}

// Class representing a bird


class Bird implements Flying {
@Override
public void fly() {
System.out.println("Bird is flying.");
}

void chirp() {
System.out.println("Bird is chirping.");
}
}

// Class representing an airplane


class Airplane implements Flying {
@Override
public void fly() {
System.out.println("Airplane is flying.");
}

void engineSound() {
System.out.println("Airplane engine sound.");
}
}

// Class representing a flying object that inherits from both Bird and Airplane through
interfaces
class FlyingObject implements Flying {
private Bird bird = new Bird();
private Airplane airplane = new Airplane();
@Override
public void fly() {
bird.fly(); // Delegating the fly behavior to Bird
airplane.fly(); // Delegating the fly behavior to Airplane
}

// Additional methods or behavior specific to FlyingObject


}

public class Main {


public static void main(String[] args) {
FlyingObject flyingObject = new FlyingObject();
flyingObject.fly(); // Calls fly() method from Bird and Airplane

// You can also access methods specific to Bird and Airplane through the FlyingObject
object
// flyingObject.chirp(); // Error: chirp() is not a method of FlyingObject
// flyingObject.engineSound(); // Error: engineSound() is not a method of FlyingObject
}
}

5. What is multithreading? Explain any two advantages of multithreading.


Ans:

 Multithreading is a function of the CPU that permits multiple threads to run independently
while sharing the same process resources. A thread is a conscience sequence of instructions
that may run in the same parent process as other threads.
 Multithreading allows many parts of a program to run simultaneously. These parts are
referred to as threads, and they are lightweight processes that are available within the
process. As a result, multithreading increases CPU utilization through multitasking. In
multithreading, a computer may execute and process multiple tasks simultaneously.

Benefits of Multithreading are

 Responsiveness
 Resource Sharing
 Economy
 Utilization of Multiprocessor Architecture

 Resource Sharing
All the threads of a process share its resources such as memory, data, files etc. A
single application can have different threads within the same address space using
resource sharing.
 Responsiveness
Program responsiveness allows a program to run even if part of it is blocked using
multithreading. This can also be done if the process is performing a lengthy
operation. For example - A web browser with multithreading can use one thread for
user contact and another for image loading at the same time.
 Utilization of Multiprocessor Architecture
In a multiprocessor architecture, each thread can run on a different processor in
parallel using multithreading. This increases concurrency of the system. This is in
direct contrast to a single processor system, where only one process or thread can
run on a processor at a time.
 Economy
It is more economical to use threads as they share the process resources.
Comparatively, it is more expensive and time-consuming to create processes as they
require more memory and resources. The overhead for process creation and
management is much higher than thread creation and management.
6. What are threads? Explain the different ways of creating threads in Java.
Ans:
The direction or path that is taken while a program is being executed is called Thread
The Different ways of creating Threads are
o By extending Thread class
o By implementing Runnable interface.

 By Extending Thread Class


STEP 1: Create a class by extending Thread Class
STEP 2: Inside a class Override run method
STEP 3:Create an Object of the class that has extended Thread class
MyThread ob=new.Mythread();
STEP 4: Start/Run the Thread
Ob.start();

EX:
class MyThread extends Thread {
MyThread(){
Super(“one”);
}
public void run (){
system.out.println(“New Thread Created “);
Thread t=Thread. current Thread();
System.out.println(t);
}
}
Public class main
{
Public static void main(string[]args){
My Thread ob=new My Thread();
Ob.start();
}
}

Output
New Thread Created
Thread[one,5,Main]

 Implementing the Runnable Interface:


STEP 1: Create a Class That implements Runnable Interface
STEP 2: Inside a class implements run() Methods
STEP 3: Create a Thread by using Thread Constructor
The Constructor of the thread as follows
Thread(Runnable Threadob,string Thread Name)
Ex: Thread t=new Thread(new myThread(),“One”)
STEP 4: Run the Thread by using start method
t.start();

EX:
class MyRunnable implements Runnable {
public void run() {
// Code to be executed by the thread
}
}

public class Main {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // Start the thread's execution
}
7. Explain the different states (Life Cycle) of the thread with a diagram.
Ans:
The Different Life Cycle of Thread are

 New: The thread is in this state when it is first created but has not yet been started by calling
its start() method.
 Runnable: Once the thread's start() method is called, it enters the runnable state. In this
state, the thread is eligible to be executed by the CPU, but it might not necessarily be
executing at any given moment due to the CPU scheduler's decisions.
 Running: A thread enters the running state when the CPU scheduler selects it for
execution. In this state, the thread's code in the run() method is actively being executed.
 Blocked/Waiting: Threads in this state are temporarily inactive. They are waiting for some
event to occur before they can proceed. This could be waiting for I/O, acquiring a lock, or
other synchronization events.
 Timed Waiting: Threads in this state are waiting for a specified amount of time. They will
automatically transition to the runnable state once the timer expires or the event they are
waiting for occurs.
 Terminated/Dead: A thread enters this state when it has completed its execution or if an
unhandled exception occurs in its code. Once a thread is terminated, it cannot be started
again.
┌──────────
│ NEW │
└───────────┘


┌───────────┐
│RUNNABLE │
└───────────┘


┌───────────┐
│ RUNNING │
└───────────┘


┌───────────┐
│ BLOCKED │
└───────────┘


┌───────────┐
│TIMED WAIT │
└───────────┘


┌───────────┐
│TERMINATED │
└───────────┘
8. Why main thread is important? Write a Java program that creates multiple child threads
and also ensures that the main thread stops last.
Ans:
The main thread in a Java program is important for several reasons:

 Program Entry Point: The main thread is where the execution of a Java program begins.
It's the first thread to be executed when you run a Java application, and it serves as the
entry point for your program.
 Control and Coordination: The main thread is responsible for coordinating the execution
of other threads in the program. It can create, start, and manage other threads, and it can
wait for their completion.
 Cleanup: The main thread is typically used to perform cleanup tasks and release resources
when the program is about to exit. This ensures that resources are properly disposed of
before the program terminates.

public class Main {


public static void main(String[] args) {
// Create an array to hold child threads
Thread[] childThreads = new Thread[5];

// Create and start child threads


for (int i = 0; i < childThreads.length; i++) {
childThreads[i] = new Thread(new ChildRunnable(i));
childThreads[i].start();
}

// Wait for all child threads to complete


for (Thread childThread : childThreads) {
try {
childThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

// Main thread's final message


System.out.println("Main thread has stopped.");
}
}

class ChildRunnable implements Runnable {


private final int id;

public ChildRunnable(int id) {


this.id = id;
}

@Override
public void run() {
System.out.println("Child Thread " + id + " is running.");
try {
Thread.sleep(2000); // Simulate some work
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Child Thread " + id + " has completed.");
}
}

9. With syntax, explain use of isalive[ ], join[ ], and yield() methods.


Ans:

I. Isalive[]
The isAlive() method is used to determine whether a thread is still active and
running. It returns true if the thread on which it's called is currently executing or has
not yet started execution, and false if the thread has finished executing.

Syntax: boolean isAlive = thread.isAlive();

Ex:
Thread thread = new Thread(() -> {
// Thread's task
});
thread.start();

boolean threadIsAlive = thread.isAlive();


System.out.println("Thread is alive: " + threadIsAlive);

II. Join[]
The join() method is used to make the calling thread wait for the thread on which
it's called to complete its execution. This is often used to ensure that specific threads
complete before the main thread continues or before another thread's execution.

Syntax: final void join() throws InterruptedException


Ex:
Thread thread1 = new Thread(() -> {
// Thread 1's task
});
Thread thread2 = new Thread(() -> {
// Thread 2's task
});
thread1.start();
thread2.start();

try {
thread1.join(); // Wait for thread1 to complete
thread2.join(); // Wait for thread2 to complete
} catch (InterruptedException e) {
e.printStackTrace();
}

III. yield() Method:


The yield() method is a hint to the scheduler that the current thread is willing to
give up its current execution slot to allow other threads to run. However, it's important
to note that the scheduler's behavior is not guaranteed, and yielding might not have a
significant impact in all situations.

Syntax: Thread.yield();

Ex:
Thread thread1 = new Thread(() -> {
// Thread 1's task
Thread.yield();
// Rest of Thread 1's task
});
Thread thread2 = new Thread(() -> {
// Thread 2's task
});

thread1.start();
thread2.start();

10. Describe the thread priority. How to assign and get the thread priority?
Ans:
Thread priority in Java is a concept that allows you to assign a priority level to each thread,
indicating its relative importance in terms of CPU time allocation. Threads with higher priority
values are more likely to be scheduled by the thread scheduler to run before threads with lower
priority values.
Java defines thread priorities using integer values ranging from Thread.MIN_PRIORITY
(1) to Thread.MAX_PRIORITY (10), with Thread.NORM_PRIORITY (5) as the default.
Higher values represent higher priority.
I. Assigning Thread Priority:
To set the priority of a thread, you can use the setPriority(int priority) method
provided by the Thread class.
Ex:
Thread thread = new Thread(() -> {
// Thread's task
});

// Set the thread's priority


thread.setPriority(Thread.MAX_PRIORITY);

thread.start();
II. Getting Thread Priority:
To retrieve the current priority of a thread, you can use the getPriority() method
provided by the Thread class.
Ex:
int priority = thread.getPriority();
System.out.println("Thread priority: " + priority);

11. What do you mean by synchronization? How it is achieved for threads in Java? Explain
with syntax.
Ans:
 Thread Synchronization is a process of allowing only one thread to use the object
when multiple threads are trying to use the particular object at the same time.
 To achieve this Thread Synchronization we have to use a java keyword or modifier
called “synchronized”.
 Synchronization in java is the capability to control the access of multiple threads to
any shared resource.
 General Syntax:
synchronized(objectidentifier)
{
// Access shared variables and other shared resources;
}
 Using the synchronized Keyword:
You can use the synchronized keyword to define critical sections of code
that should be accessed by only one thread at a time. This can be applied to methods
or blocks of code.
class SharedResource {
private int count = 0;

public synchronized void increment() {


count++;
}
}
 Using Locks from java.util.concurrent Package:

The java.util.concurrent package provides more advanced synchronization


mechanisms, such as explicit locks (ReentrantLock) and read-write locks
(ReadWriteLock). These locks offer finer control over synchronization and can be
more flexible in certain scenarios.

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SharedResource {
private Lock lock = new ReentrantLock();
private int count = 0;

public void increment() {


lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
12. Describe Inter-thread Communication in Java? How to avoid polling by using an inter-
process communication mechanism.
Ans:
It is a mechanism in which a thread is paused running in its critical section and
another thread is allowed to enter (or lock) in the same critical section to be executed.It is
implemented by following methods of Object class:
o wait()
o notify()
o notifyAll()

 wait(): It tells the calling thread to give up the lock and go to sleep until some other thread
enters the same monitor and calls notify().
 notify(): It wakes up one single thread called wait() on the same object. It should be noted
that calling notify() does not give up a lock on a resource.
Syntax:public final void notify()
 notifyAll(): It wakes up all the threads called wait() on the same object.
Syntax:public final void notifyAll()
13. Write a short note on the Bounded buffer problem.
Or
14. With suitable examples explain the Producer-Consumer problem.
Ans:
 The Bounded buffer Problem can also be called a Producer consumer problem. The
problem covers two processes—the producer and the consumer—that share a single, fixed-
size buffer that serves as a queue.
o Data generation, buffering, and restarting are all tasks performed by the producer.
o The consumer simultaneously consumes the data (i.e., removed from the buffer),
one piece at a time.
 The producer must either sleep or destroy data when the buffer is full. When a consumer
later takes an item out of the buffer, the producer is notified, and the buffer is once more
filled. In the same way, if the consumer detects that the buffer is empty, it can nod off. The
consumer is awakened when the producer inserts data into the buffer to find significance.

 Buffer Data Structure: The buffer is a shared data structure that can hold a fixed number
of items. Both producer and consumer threads interact with this buffer.
 Producer Threads: These threads are responsible for adding items to the buffer. They
need to ensure that they don't add items when the buffer is full.
 Consumer Threads: These threads are responsible for removing items from the buffer.
They should wait when the buffer is empty.
 Synchronization Mechanisms: To avoid race conditions and coordinate the behavior of
producer and consumer threads, synchronization mechanisms like locks, semaphores, or
condition variables are commonly used.
 Deadlocks and Starvation: Incorrect synchronization can lead to deadlocks, where
threads are blocked indefinitely. Starvation might occur if certain threads are consistently
unable to access resources.

// Java program to implement solution of producer


import java.util.LinkedList;

public class Threadexample {


public static void main(String[] args)
throws InterruptedException
{
final PC pc = new PC();
Thread t1 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.produce();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run()
{
try {
pc.consume();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t1.start();
t2.start();
t1.join();
t2.join();
}
public static class PC {
LinkedList<Integer> list = new LinkedList<>();
int capacity = 2;
public void produce() throws InterruptedException
{
int value = 0;
while (true) {
synchronized (this)
{
while (list.size() == capacity)
wait();
System.out.println("Producer produced-" + value);
list.add(value++);
notify();
Thread.sleep(1000);
}
}
}
public void consume() throws InterruptedException
{
while (true) {
synchronized (this)
{
while (list.size() == 0)
wait();
int val = list.removeFirst();

System.out.println("Consumer consumed-"+ val);


notify();
Thread.sleep(1000);
}
}
}
}
}

You might also like