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

Java IA3 Question Bank_vamshi

The document provides an overview of exceptions in Java, differentiating between checked and unchecked exceptions, and explains the use of try, catch, and finally blocks for handling exceptions. It also covers the creation of user-defined exceptions, the importance of the Throwable class methods, and the differences between processes and threads. Additionally, it illustrates how to create multiple threads using the Thread class and the Runnable interface with examples.

Uploaded by

amdvamshi.genai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java IA3 Question Bank_vamshi

The document provides an overview of exceptions in Java, differentiating between checked and unchecked exceptions, and explains the use of try, catch, and finally blocks for handling exceptions. It also covers the creation of user-defined exceptions, the importance of the Throwable class methods, and the differences between processes and threads. Additionally, it illustrates how to create multiple threads using the Thread class and the Runnable interface with examples.

Uploaded by

amdvamshi.genai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

1. Define an Exception.

Differentiate between uncaught(unchecked) and


caught(checked) exception.
An exception is an abnormal condition that arises in a code sequence at run time1.
In other words, an exception is a run time error1.
Java includes the built-in class Throwable2. All exception types are subclasses of
Throwable3. Immediately below Throwable are two subclasses: Exception and
Error3.
Exception is used for exceptional conditions that user programs should catch3. This
is also the class that you will subclass to create your own custom exception types3.
RuntimeException is an important subclass of Exception3. Exceptions of this type are
automatically defined for the programs that you write and include things such as
division by zero and invalid array indexing4.
Error defines exceptions that are not expected to be caught under normal
circumstances by your program4. Exceptions of type Error are used by the Java run-
time system to indicate errors having to do with the run-time environment, itself4.
Stack overflow is an example of such an error4.
The exceptions defined in java.lang that must be included in a method’s throws list
(if that method can generate one of these exceptions and does not handle it itself)
are called checked exceptions5. Unchecked exceptions are not checked by the
compiler to see if a method handles or throws them
Explain the use of try and catch and finally features with example
The try, catch, and finally blocks are essential features in programming languages like Java,
C#, and Python (with slightly different syntax). They help handle exceptions or errors
gracefully, ensuring that the program doesn't crash unexpectedly and necessary cleanup
operations can still be performed.
Here’s a detailed explanation of each:

1. try Block
The try block contains the code that might cause an exception. If an error occurs, the
exception is thrown, and control is transferred to the appropriate catch block.

2. catch Block
The catch block handles the exception thrown by the try block. You can specify different
types of exceptions and provide customized handling for each type.

3. finally Block
The finally block contains code that is always executed, regardless of whether an exception
occurs or not. This is typically used for cleanup actions like closing files, releasing resources,
or closing database connections.

Syntax Example in Java


public class TryCatchFinallyExample {
public static void main(String[] args) {
try {
// Code that may cause an exception
int result = 10 / 0; // This will throw an ArithmeticException
System.out.println("Result: " + result); // This line will not be executed
} catch (ArithmeticException e) {
// Handling the specific exception
System.out.println("Error: Division by zero is not allowed.");
} finally {
// This block will always be executed
System.out.println("Execution complete. Cleaning up resources.");
}
}
}

Differentiate between throw and throws keyword with an example


Feature throw throws
Declares exceptions that a
Purpose Used to explicitly throw an exception.
method might throw.
Used in the method
Placement Used inside a method or a block.
signature.
Exception Can declare multiple
Can throw only one exception at a time.
Type exceptions.
methodName() throws
Syntax throw new ExceptionType("message");
ExceptionType { ... }
throw new
public void method()
Example ArithmeticException("Division by
throws IOException
zero");
Explain with example how to create user defined exception.
🔹 Steps to Create a User-Defined Exception
1. Create a Class for the Custom Exception:
o Extend Exception for checked exceptions or RuntimeException for unchecked
exceptions.
o Define constructors to pass messages or other details.
2. Throw the Custom Exception:
o Use the throw keyword to explicitly throw the custom exception.
3. Handle the Custom Exception:
o Use a try-catch block to catch and handle the custom exception.

🔹 Example of a User-Defined Exception


Scenario:
Suppose we are building a banking application where a withdrawal should not be
allowed if the amount exceeds the account balance. We'll create a custom exception
InsufficientFundsException to handle this situation.
1. Define the User-Defined Exception
// Custom exception class
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
2. Use the Custom Exception in a Bank Account Class
java
Copy code
public class BankAccount {
private double balance;

public BankAccount(double balance) {


this.balance = balance;
}

// Method to withdraw money


public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Withdrawal amount exceeds the
current balance.");
}
balance -= amount;
System.out.println("Withdrawal successful. Remaining balance: $" + balance);
}

public static void main(String[] args) {


BankAccount account = new BankAccount(500);

try {
System.out.println("Attempting to withdraw $600...");
account.withdraw(600); // This will throw an InsufficientFundsException
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
}

try {
System.out.println("Attempting to withdraw $300...");
account.withdraw(300); // This will succeed
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Develop a JAVA program to raise a custom exception (user defined exception) for
DivisionbyZero using try , catch , throw, throws and finally
class DivisionByZeroException extends Exception
{
public DivisionByZeroException(String message)
{
super(message);
}
}
public class CustomExceptionExample
{
public static void main(String[] args)
{
try {
int dividend = 10;
int divisor = 0;

if (divisor == 0)
{
throw new DivisionByZeroException("Division by zero is not allowed");
}

int result = dividend / divisor;


System.out.println("Result: " + result);
}
catch (DivisionByZeroException e)
{
System.err.println("Custom Exception: " + e.getMessage());
} catch (ArithmeticException e)
{
System.err.println("Arithmetic Exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed.");
}
}
}
Explain the important methods in the Throwable class
🔹 Important Methods in the Throwable Class
1. getMessage()
 Purpose: Returns the detail message string associated with the Throwable.
 Use Case: To retrieve a description of the exception/error.
Example:
java
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error Message: " + e.getMessage());
}
Output:
vbnet
Error Message: / by zero

2. getLocalizedMessage()
 Purpose: Returns a localized description of the exception/error message.
 Use Case: Useful for internationalization (i18n) where error messages need to
be in different languages.
Example:
try {
throw new Exception("File not found");
} catch (Exception e) {
System.out.println("Localized Message: " + e.getLocalizedMessage());
}
Output:
mathematica
Localized Message: File not found

3. printStackTrace()
 Purpose: Prints the stack trace of the Throwable to the standard error stream
(or another output stream).
 Use Case: To debug and understand where the exception occurred.
Example:
java
Copy code
try {
String str = null;
str.length();
} catch (NullPointerException e) {
e.printStackTrace();
}
Sample Output:
css
Copy code
java.lang.NullPointerException
at Main.main(Main.java:5)

4. toString()
 Purpose: Returns a string representation of the Throwable, which includes the
exception's class name and the detail message.
 Use Case: Provides a concise description of the exception.
Example:
java
Copy code
try {
int[] numbers = new int[2];
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.toString());
}
Output:
makefile
Copy code
java.lang.ArrayIndexOutOfBoundsException: 5

5. getStackTrace()
 Purpose: Returns an array of StackTraceElement objects representing the stack
trace.
 Use Case: To programmatically analyze the stack trace.
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
StackTraceElement[] stackTrace = e.getStackTrace();
for (StackTraceElement element : stackTrace) {
System.out.println(element);
}
}
Sample Output:
css
Copy code
Main.main(Main.java:4)

6. setStackTrace(StackTraceElement[] stackTrace)
 Purpose: Modifies the stack trace of the Throwable.
 Use Case: To manipulate or modify the stack trace before displaying it (useful
in logging or debugging).
Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
e.setStackTrace(new StackTraceElement[] {
new StackTraceElement("CustomClass", "customMethod", "CustomFile.java",
123)
});
e.printStackTrace();
}
Output:
csharp
java.lang.ArithmeticException: / by zero
at CustomClass.customMethod(CustomFile.java:123)

7. getCause()
 Purpose: Returns the cause of the Throwable, or null if the cause is unknown.
 Use Case: To identify the underlying cause of an exception.
Example:
java
try {
throw new RuntimeException("Top-level exception", new
IllegalArgumentException("Cause of the problem"));
} catch (RuntimeException e) {
System.out.println("Cause: " + e.getCause());
}
Output:
makefile
Copy code
Cause: java.lang.IllegalArgumentException: Cause of the problem

8. initCause(Throwable cause)
 Purpose: Sets the cause of the Throwable. Used to chain exceptions.
 Use Case: To associate a secondary exception as the cause of a primary
exception.
Example:
try {
NullPointerException npe = new NullPointerException("Null pointer occurred");
npe.initCause(new IllegalArgumentException("Invalid argument passed"));
throw npe;
} catch (NullPointerException e) {
System.out.println("Exception: " + e);
System.out.println("Cause: " + e.getCause());
}
Output:
yaml
Copy code
Exception: java.lang.NullPointerException: Null pointer occurred
Cause: java.lang.IllegalArgumentException: Invalid argument passed

9. fillInStackTrace()
 Purpose: Reinitializes the stack trace of the Throwable to the current thread's
stack trace.
 Use Case: To reset the stack trace to reflect the current execution context.
Example:
try {
throw new Exception("Initial Exception");
} catch (Exception e) {
e.fillInStackTrace();
e.printStackTrace();
}
Differentiate between process and thread.
Aspect Process Thread
A process is an independent A thread is the smallest unit of
execution unit that contains execution within a process.
Definition
its own memory space and Threads within the same
resources. process share resources.
Threads share the same
Memory Each process has its own
memory space within a
Space separate memory space.
process.
Threads can
Inter-process communication
communicate directly by
Communication (IPC) is needed to share data
sharing variables and
between processes.
memory.
Creating a process is expensive Creating a thread is
Creation
and slow due to memory relatively fast and has
Overhead
allocation and OS overhead. low overhead.
Context switching between Context switching between
Context processes is slower due to threads is faster because
Switching separate memory space and threads share the same
resources. memory.
Processes are independent of Threads within the same
Independence each other and can run process are dependent on
separately. each other.
Each process has its own Threads share the process's
Resource
resources, such as file resources but have their own
Allocation
handles and CPU registers. execution stack and registers.
Fault A failure in one process does A failure in one thread can
Isolation not affect other processes. affect the entire process.
Running two separate Downloading a file while playing a video
Example applications (e.g., a web in a media player (multiple threads within
browser and a text editor). one application).

Explain with example how the main method is also a thread.


When a Java program starts up, one thread begins running immediately. This is called
the main thread because it is the one that is executed when your program begins.
The main thread is important because it is the thread from which other "child"
threads will be spawned. It often must be the last thread to finish execution because
it performs various shutdown actions.
Although the main thread is created automatically when your program starts, you
can control it just like any other thread by using a Thread object. To obtain a
reference to the main thread, you must call the method currentThread(), which is a
public static member of Thread.
static Thread currentThread( )
This method will return a reference to the thread in which it is called. Once you have
the reference to the main thread, you can control it like any other thread.
You can use the isAlive() and join() methods of the Thread class to ensure that the
main thread is the last thread to finish.

Explain how to create multiple threads using the Thread class with an
example
The easiest way to create a thread is to create a class that implements the Runnable
interface. The Runnable interface abstracts a unit of executable code. You can
construct a thread on any object that implements Runnable.
To implement Runnable, a class only needs to implement a single method called
run().
public void run( )
Inside run(), you will define the code that constitutes the new thread. The run()
method can call other methods, use other classes, and declare variables. The run()
method establishes the entry point for another, concurrent thread of execution
within your program. This thread will end when run() returns.
After you create a class that implements Runnable, you will instantiate an object of
type Thread from within that class. The Thread class defines several constructors.
The constructor shown below takes an instance of a class that implements the
Runnable interface and a string that specifies the name of the new thread.
Thread(Runnable threadOb, String threadName)
After the new thread is created, it will not start running until you call its start()
method, which is declared within the Thread class. The start() method executes a call
to run().
void start( )
Example
class MyThread implements Runnable {
Thread thrd;

// Construct a new thread.


MyThread(String name) {
thrd = new Thread(this, name);
thrd.start(); // start the thread
}

// Begin execution of new thread.


public void run() {
System.out.println(thrd.getName() + " starting.");
try {
for(int count=0; count < 10; count++) {
Thread.sleep(400);
System.out.println("In " + thrd.getName() +
", count is " + count);
}
}
catch(InterruptedException exc) {
System.out.println(thrd.getName() + " interrupted.");
}
System.out.println(thrd.getName() + " terminating.");
}
}

class MoreThreads {
public static void main(String args[]) {
System.out.println("Main thread starting.");

MyThread mt1 = new MyThread("Child #1");


MyThread mt2 = new MyThread("Child #2");
MyThread mt3 = new MyThread("Child #3");

try {
for(int count=0; count < 10; count++) {
Thread.sleep(400);
System.out.print(".");
}
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread ending.");
}
}

1. Explain how to create multiple threads using the Runnable


interface with an example
The easiest way to create a thread is to create a class that implements the
Runnable interface. The Runnable interface abstracts a unit of executable
code. You can construct a thread on any object that implements Runnable.
To implement Runnable, a class only needs to implement a single method
called run().
public void run( )
Inside run(), you will define the code that constitutes the new thread. The
run() method can call other methods, use other classes, and declare
variables. The run() method establishes the entry point for another,
concurrent thread of execution within your program. This thread will end
when run() returns.1
After you create a class that implements Runnable, you will instantiate an
object of type Thread from within that class. The Thread class defines several
constructors. One of the constructors is shown below.2
Thread(Runnable threadOb, String threadName)
This constructor takes an instance of a class that implements the Runnable
interface and a string that specifies the name of the new thread.
After the new thread is created, it will not start running until you call its
start() method, which is declared within the Thread class. The start() method
executes a call to run().3
void start( )
Example
class MyThread implements Runnable {
Thread thrd;

// Construct a new thread.


MyThread(String name) {
thrd = new Thread(this, name);
thrd.start(); // start the thread
}

// Begin execution of new thread.


public void run() {
System.out.println(thrd.getName() + " starting.");
try {
for(int count=0; count < 10; count++) {
Thread.sleep(400);
System.out.println("In " + thrd.getName() +
", count is " + count);
}
}
catch(InterruptedException exc) {
System.out.println(thrd.getName() + " interrupted.");
}
System.out.println(thrd.getName() + " terminating.");
}
}

class MoreThreads {
public static void main(String args[]) {
System.out.println("Main thread starting.");

MyThread mt1 = new MyThread("Child #1");


MyThread mt2 = new MyThread("Child #2");
MyThread mt3 = new MyThread("Child #3");

try {
for(int count=0; count < 10; count++) {
Thread.sleep(400);
System.out.print(".");
}
}
catch(InterruptedException exc) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread ending.");
}
}

Explain few important methods of the Thread class


Here are some of the most important methods of the Thread class:

run() - This method is the entry point for the new thread. Inside run(), you will define the
code that makes up the new thread. The run() method can call other methods, use other
classes, and declare variables just like the main thread can. The only difference is that run()
establishes the entry point for another concurrent thread of execution within your
program. This thread will end when run() returns.1

start() - After you create a new thread, it won't start running until you call its start() method.
The start() method executes a call to run().2

currentThread() - This method returns a reference to the thread in which it is called. This
allows the programmer to manipulate the current thread, such as getting its name, setting
its priority, or putting it to sleep.3

isAlive() - This method returns true if the thread upon which it is called is still running. It
returns false otherwise. This method can be used to determine if a thread has finished
executing.4

join() - This method waits until the thread on which it is called terminates. This method's
name comes from the concept of the calling thread waiting until the specified thread joins it.
This method can be used to ensure that one thread finishes before another thread
continues. For example, the main thread might want to wait for a child thread to finish
before it prints out a final result.5

sleep() - This method causes the currently executing thread to sleep (temporarily cease
execution) for the specified number of milliseconds. This method is useful for pausing
execution of a thread for a specific amount of time. For example, you might use sleep() to
create a delay between iterations of a loop.

Explain the use of wait(),notify() and notifyAll() methods


To avoid polling, Java includes an elegant inter-process communication mechanism via the
wait(), notify(), and notifyAll() methods12. These methods are implemented as final
methods in Object, so all classes have them2. All three methods can be called only from
within a synchronized context2.
The rules for using these methods are quite simple:

wait() - A thread enters a monitor by calling a synchronized method. If a condition required
by the thread is not met, the thread can call wait() to release the monitor and wait until it is
notified that the condition has changed12.

notify() - Another thread can enter the monitor, change the condition, and call notify() to
awaken one of the threads that are waiting12.

notifyAll() - Another thread can enter the monitor, change the condition, and call notifyAll()
to awaken all of the threads that are waiting12.
Although wait() normally waits until notify() or notifyAll() is called, there is a possibility that
the waiting thread could be awakened due to a spurious wakeup3. This means that a waiting
thread resumes without notify() or notifyAll() having been called. Oracle recommends that
calls to wait() should take place within a loop that checks the condition on which the thread
is waiting

1.
2.
3.
4.
5.
6.
7.
8.
9. Explain the concept of synchronization with example
10. Write a program to illustrate creation of threads using runnable interface .(Using start()
method start each of the newly created thread .Inside the run method there is sleep() for
suspend the thread for 500 milliseconds)
11. Develop a program to create a class MyThread in this class a constructor , call the base class
constructor, using super and start the thread . The run method of the class starts after this. It
can be observed that both main thread and created thread are excecuting concurrently.
12. Explain the exceptions ArrayIndexOutofBoundsException and ArithmeticException.
13. Explain the class hierarchy specific to exception handling.

18.Explain the concept of thread priority with an example?


19. Explain the following methods in the Thread class
a.setPriority() getPriority()
b.setName() getName()
c.start()
d.run()
e.sleep()
f. join()
20. What is enumeration?Explain the use of values() and valueOf() method.
21. Write a note on Wrapper classes.
22.Explain autoboxing and un boxing with example
23. Differentiate between final finally and finalize()

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy