Unit Iii Q & A
Unit Iii Q & A
2. List the values associated with the parameters of setpriority() method of Thread
class. Apr/May 2023
The priority values Java, the Thread class has a method named setPriority (int
newPriority) that allows you to set the priority of a thread. The priority of a thread
affects its scheduling relative to other threads. Java provides a range of priority values
that you can use with the setPriority method. for threads in Java are defined as
constants in the Thread class:
1. Thread.MIN_PRIORITY: Represents the minimum priority value a thread
can have. The value is 1.
2. Thread.NORM_PRIORITY: Represents the default priority value for
threads. The value is 5.
3. Thread.MAX_PRIORITY: Represents the maximum priority value a thread
can have. The value is 10.
4. What is Thread priority? How it can be set for a Thread? Apr/May 2024
Thread priority is a mechanism in Java that allows you to influence the scheduling
order of threads. Each thread in Java can be assigned a priority, which is a number
indicating the relative importance of the thread compared to other threads. This
priority affects how the Java Virtual Machine (JVM) schedules threads for execution.
Setting Thread Priority
To set the priority of a thread in Java, you use the setPriority(int newPriority) method
of the Thread class. The priority value must be between Thread.MIN_PRIORITY and
Thread.MAX_PRIORITY, inclusive.
10. Name the methods used by Java for interprocess communication to avoid
polling. Nov/Dec 2023
Interprocess communication (IPC) is a crucial aspect of developing applications that
need to coordinate or share data between different processes. To avoid the
inefficiency of polling, Java provides several mechanisms for interprocess
communication.
PART B(5 X 13 =65)
1. Discuss about user defined exceptions in Java. Give suitable examples. Apr/May 2024
User-defined exceptions in Java allow you to create custom exception classes that
represent specific error conditions in your application. These exceptions extend the built-in
Exception class or one of its subclasses, enabling you to handle application-specific scenarios
in a meaningful way.
Why Use User-Defined Exceptions?
1. Clarity: Custom exceptions make your code more readable by providing meaningful
names and messages for specific error conditions.
2. Control: They allow you to handle specific exceptions more precisely and provide
tailored responses.
3. Separation: They help in separating different types of errors and their handling logic,
improving maintainability.
Creating User-Defined Exceptions
To create a user-defined exception in Java, follow these steps:
1. Extend the Exception Class:
o Create a new class that extends the Exception class (or a subclass like
RuntimeException if you want it to be an unchecked exception).
2. Define Constructors:
o Provide constructors to initialize the exception with a message and/or a cause.
You can use the default constructor, a constructor with a message, or a
constructor with both a message and a cause.
3. Add Additional Methods (if needed):
o You can add additional methods or fields if your exception needs extra
information.
Example of User-Defined Exception
Let’s create a custom exception called InsufficientFundsException for a banking application
where a withdrawal operation cannot be completed due to insufficient funds.
Define the Custom Exception:
// File: InsufficientFundsException.java
public class InsufficientFundsException extends Exception
{
// Default constructor
public InsufficientFundsException()
{s
uper();
}
// Constructor that accepts a message
public InsufficientFundsException(String message)
{
super(message);
}
// Constructor that accepts a message and a cause
public InsufficientFundsException(String message, Throwable cause)
{
super(message, cause);
}
// Constructor that accepts a cause
public InsufficientFundsException(Throwable cause) { super(cause);
}
}
2. How Thread Synchronization is managed in Java. Write example code. Apr/May
2024
Thread synchronization in Java is a mechanism used to ensure that multiple threads can
safely access and modify shared resources or data without causing data inconsistency or
corruption. Synchronization is crucial when multiple threads interact with shared data to
avoid issues like race conditions.
Key Concepts of Thread Synchronization
1. Critical Section:
o A block of code that accesses shared resources and must be executed by only
one thread at a time.
2. Synchronization:
o The process of controlling access to critical sections to ensure that only one
thread executes a critical section at any given time.
3. Monitor:
o Java provides a built-in monitor for every object. When a thread locks an
object’s monitor, no other thread can access the synchronized methods or
blocks of that object until the lock is released.
Mechanisms for Synchronization in Java
1. Synchronized Methods:
o Methods can be declared synchronized to ensure that only one thread executes
the method on a particular object at a time.
2. Synchronized Blocks:
o Blocks of code within a method can be synchronized to allow more granular
control over synchronization.
3. Locks:
o The java.util.concurrent.locks package provides explicit locking mechanisms
through classes like ReentrantLock and ReadWriteLock.
Example of Synchronization with Synchronized Methods
Here is a simple example demonstrating thread synchronization using synchronized methods:
Example Code:
java
Copy code
// File: Counter.java
public class Counter {
private int count = 0;
// Synchronized method to ensure only one thread updates the count at a time
public synchronized void increment() {
count++;
}
// File: CounterTest.java
public class CounterTest {
public static void main(String[] args) {
Counter counter = new Counter();
try {
// Wait for both threads to finish
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
3. Explain detain about Java Built in exceptions. Explain any three exceptions. Apr/May
2023
Java built-in exceptions are a part of the Java Standard Library and are used to handle various
error conditions that can occur during the execution of a program. These exceptions are
subclasses of java.lang.Exception and are designed to address common issues like invalid
input, resource unavailability, and arithmetic errors.
Java Built-In Exception Hierarchy
The Java exception hierarchy is structured as follows:
java.lang.Throwable
o java.lang.Exception
java.lang.RuntimeException
java.lang.NullPointerException
java.lang.ArithmeticException
java.lang.ArrayIndexOutOfBoundsException
java.lang.IllegalArgumentException
java.lang.NumberFormatException
java.io.IOException
java.lang.ClassNotFoundException
java.lang.NoSuchMethodException
java.lang.InterruptedException
java.lang.FileNotFoundException
Examples of Built-In Exceptions
Let's discuss three commonly encountered built-in exceptions:
1. ArithmeticException
Description:
Type: Runtime Exception
Cause: Thrown when an exceptional arithmetic condition has occurred, such as
division by zero.
Example:
java
Copy code
public class ArithmeticExceptionExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
int result = a / b; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
}
}
Explanation:
In this example, dividing 10 by 0 throws an ArithmeticException. The catch block
handles the exception and prints an error message.
2. NullPointerException
Description:
Type: Runtime Exception
Cause: Thrown when the application attempts to use null where an object is required.
For example, accessing a method or field on a null reference.
Example:
java
Copy code
public class NullPointerExceptionExample {
public static void main(String[] args) {
String str = null;
try {
int length = str.length(); // This will throw NullPointerException
} catch (NullPointerException e) {
System.out.println("Error: Attempted to access method on a null object.");
}
}
}
3. ArrayIndexOutOfBoundsException
Description:
Type: Runtime Exception
Cause: Thrown when an application attempts to access an array with an illegal index.
For example, accessing an index that is negative or beyond the array's length.
Example:
java
Copy code
public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
int[] array = {1, 2, 3};
try {
int value = array[5]; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Array index is out of bounds.");
}}}
In Java, there are two primary ways to create and run threads: by extending the Thread class
and by implementing the Runnable interface. Both approaches enable concurrent execution of
code, but they differ in their implementation details and use cases. Let’s discuss both methods
in detail.
1. Extending the Thread Class
To create a thread by extending the Thread class, you need to follow these steps:
1. Extend the Thread Class:
o Create a new class that extends the Thread class.
o Override the run() method to define the code that will be executed by the
thread.
2. Create an Instance and Start the Thread:
o Instantiate your custom thread class.
o Call the start() method on the thread instance to begin execution.
Example:
// File: MyThread.java
public class MyThread extends Thread {
@Override
public void run() {
// Code to be executed by the thread
for (int i = 0; i < 5; i++) {
System.out.println("Thread is running: " + i);
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
Integer result = futureTask.get(); // Retrieve result from the callable task
System.out.println("Result from callable: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
2. Using ExecutorService:
o Provides a higher-level replacement for managing threads and task execution
with a thread pool.
Example:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
executor.execute(task1);
executor.execute(task2);
executor.shutdown();
}}
5. Discuss about try, catch and finally keywords in Exception handling with an example.
In Java, the try, catch, and finally keywords are used to handle exceptions and ensure that
specific code is executed regardless of whether an exception occurs. These keywords form
the core of Java's exception handling mechanism, allowing developers to manage runtime
errors effectively.
Overview of try, catch, and finally
1. try Block:
o The try block contains code that might throw an exception. It is used to wrap
the code that you want to monitor for exceptions.
2. catch Block:
o The catch block is used to handle the exception thrown by the try block. You
can have multiple catch blocks to handle different types of exceptions. Each
catch block specifies a type of exception and provides a way to respond to that
exception.
3. finally Block:
o The finally block contains code that is executed after the try and catch blocks,
regardless of whether an exception was thrown or not. It is typically used for
cleaning up resources like closing files or releasing database connections.
Basic Syntax
try {
// Code that might throw an exception
} catch (ExceptionType1 e1) {
// Code to handle ExceptionType1
} catch (ExceptionType2 e2) {
// Code to handle ExceptionType2
} finally {
// Code that will always be executed
}
Example: File Reading with Exception Handling
Here is an example that demonstrates the use of try, catch, and finally for handling exceptions
while reading from a file:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
try {
// Attempt to open and read from the file
reader = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// Handle file I/O exceptions
System.out.println("An error occurred while reading the file: " + e.getMessage());
} finally {
// Ensure the file reader is closed
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.out.println("An error occurred while closing the file: " +
e.getMessage());
}
}
}
}
}
Explanation
1. try Block:
o The try block attempts to open and read from a file using BufferedReader and
FileReader. If the file does not exist or there is an issue reading the file, an
IOException may be thrown.
2. catch Block:
o The catch block catches IOException if an error occurs during file reading. It
prints an error message to indicate the problem.
3. finally Block:
o The finally block ensures that the BufferedReader is closed, regardless of
whether an exception was thrown or not. This is important to prevent resource
leaks. If closing the reader itself throws an exception, it is caught and handled
inside another try-catch block within the finally block.
Key Points
Execution Order:
o The finally block is always executed after the try block and any catch blocks,
even if no exception is thrown. It is not executed if the JVM shuts down or if
the thread executing the try block is terminated.
Resource Management:
o The finally block is commonly used for resource management, such as closing
files, releasing database connections, or cleaning up resources.
Multiple catch Blocks:
o You can have multiple catch blocks to handle different types of exceptions.
The order of catch blocks is important; more specific exceptions should be
caught before more general ones.
Re-throwing Exceptions:
o If you need to re-throw an exception after handling it in the catch block, you
can use the throw keyword. This can be useful for logging exceptions and then
propagating them.
catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
throw e; // Re-throw the exception
}
PART C (1 x 15)
Case study 1:
create software departmental stores to maintain the following details like item_no,
item_description, requested quantity, cost price provide the options to upadate the stock
calculate the selling price(SP=CP*20%). Create an exception whenever the selling price
of item exceeds the given amount.
Custom Exception Class
Define a custom exception for handling cases where the selling price exceeds a specified
amount.
java
Copy code
// File: PriceExceededException.java
public class PriceExceededException extends Exception {
public PriceExceededException(String message) {
super(message);
}
}
Item Class
Create a class to represent an item and handle the required operations.
java
Copy code
// File: Item.java
public class Item {
private int item_no;
private String item_description;
private int requested_quantity;
private double cost_price;
// Sample data
store.addItem(new Item(1, "Laptop", 10, 150.00));
store.addItem(new Item(2, "Mouse", 50, 20.00));
while (true) {
System.out.println("Departmental Store Menu:");
System.out.println("1. Update Stock");
System.out.println("2. Display Item Details");
System.out.println("3. Validate and Display Selling Price");
System.out.println("4. Exit");
System.out.print("Choose an option: ");
switch (choice) {
case 1:
System.out.print("Enter Item No: ");
int itemNoForUpdate = scanner.nextInt();
System.out.print("Enter New Quantity: ");
int newQuantity = scanner.nextInt();
store.updateStock(itemNoForUpdate, newQuantity);
break;
case 2:
System.out.print("Enter Item No: ");
int itemNoForDetails = scanner.nextInt();
store.displayItemDetails(itemNoForDetails);
break;
case 3:
System.out.print("Enter Item No: ");
int itemNoForValidation = scanner.nextInt();
store.validateAndDisplaySellingPrice(itemNoForValidation);
break;
case 4:
System.out.println("Exiting...");
scanner.close();
return;
default:
System.out.println("Invalid option. Please try again.");
}
}
}
}
Case Study 2:
Define Wrapper class. Give the following wrapper class method with syntax and use
1. To convert integer number of string
2. To convert numeric string to integer number
1. To convert integer number of string
In Java, the Integer wrapper class provides a method to convert a String to an int. The
Integer.parseInt(String s) method is used for this purpose. This method takes a String
argument and converts it into an int. It throws a NumberFormatException if the String is not
a valid representation of an integer.
Here's a detailed explanation and example of how to use this method:
Using Integer.parseInt(String s)
Method Signature
java
Copy code
public static int parseInt(String s) throws NumberFormatException
Parameters
s: A String containing the integer representation to be parsed.
Returns
An int representing the integer value of the specified String.
Throws
NumberFormatException: If the String cannot be parsed as an integer.
Example Code
Here's an example that demonstrates how to use Integer.parseInt(String s) to convert a String
to an int:
java
Copy code
public class StringToIntegerExample {
public static void main(String[] args) {
try {
// Example 1: Converting a valid integer string
String numberStr = "12345";
int number = Integer.parseInt(numberStr);
System.out.println("Converted number: " + number); // Output: 12345
} catch (NumberFormatException e) {
System.out.println("Error: The provided string is not a valid integer.");
e.printStackTrace();
}
}
}
Explanation of the Code
1. Valid Integer String Conversion:
o String numberStr = "12345";
o int number = Integer.parseInt(numberStr);
o The parseInt method converts the string "12345" to the integer 12345.
2. Valid Negative Integer String Conversion:
o String negativeNumberStr = "-6789";
o int negativeNumber = Integer.parseInt(negativeNumberStr);
o The parseInt method correctly handles negative numbers and converts "-6789"
to the integer -6789.
3. Handling Invalid Input:
o String invalidNumberStr = "123abc";
o int invalidNumber = Integer.parseInt(invalidNumberStr);
o Since "123abc" is not a valid integer representation, parseInt throws a
NumberFormatException. This exception is caught and handled in the catch
block, where an error message is printed.
} catch (NumberFormatException e) {
System.out.println("Error: The provided string is not a valid integer.");
e.printStackTrace();
}
}
}