javaans
javaans
javaans
An exception is an event or an error that disrupts the normal flow of the program’s execution.
Exceptions can occur due to various reasons, such as invalid user input, network failures, or file-
related errors.
• Exception: An object representing an error or event that can be handled by the program.
Example: ArithmeticException.
• Throws: Specifies which exceptions a method might throw, allowing the caller of the method
to handle them. Example: public void myMethod() throws IOException.
• Try: A block of code where exceptions might occur, and the code that handles them is placed
inside catch blocks.
• Catch: Defines what to do if an exception is thrown inside the try block. Example: catch
(ArithmeticException e) { ... }.
• Finally: A block of code that is always executed after the try block, whether an exception
occurs or not. Example: finally { ... }.
Example:
java
Copy code
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
} finally {
A user-defined exception is a custom exception class that extends the Exception class.
Example:
java
Copy code
super(message);
try {
withdraw(1000, 2000);
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
} else {
System.out.println("Withdrawal successful!");
• Built-in Exception: These are pre-defined exceptions in Java, part of the java.lang package.
Examples include NullPointerException, IOException, ArithmeticException, etc.
java
Copy code
In the above example, if there's no try-catch block, it will terminate the program with an uncaught
exception.
Chained exceptions are used when one exception is caused by another exception. You can link
multiple exceptions together, allowing you to track the cause of an error through multiple layers.
Example:
java
Copy code
try {
try {
} catch (ArithmeticException e) {
} catch (NullPointerException e) {
In this example, the NullPointerException is caused by the ArithmeticException, and you can track it
using getCause().
java
Copy code
try {
throwIllegalAccess();
} catch (IllegalAccessException e) {
In this example, a custom exception InsufficientBalanceException is thrown if the balance is less than
the minimum required balance.
Example:
java
Copy code
super(message);
class BankAccount {
private double balance;
this.balance = initialBalance;
balance -= amount;
try {
account.withdraw(600);
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
In this program, the withdraw method checks if the balance after withdrawal is above the minimum
required balance (MIN_BALANCE). If not, it throws an InsufficientBalanceException.
Summary of Exceptions:
1. User-Defined Exception: You can create your own exception classes by extending the
Exception class.
4. Uncaught Exception: An exception that is not handled and leads to program termination.
1. What is Multithreading? Write a Program to Create Multiple Threads in JAVA
Multithreading is the ability of a CPU to provide multiple threads of execution concurrently, where
each thread runs as an independent process. It allows a program to perform multiple tasks
simultaneously, making it more efficient.
java
Copy code
t1.start();
t2.start();
t3.start();
In this example, three threads (t1, t2, and t3) are created, and all run concurrently.
2. What Do You Mean by a Thread? Explain the Different Ways of Creating Threads.
A thread is a single sequence of execution in a program. It is the smallest unit of CPU execution.
Every Java program has at least one thread, known as the main thread.
o Create a new class that extends Thread and override its run() method.
o Then, create an object of the class and call start() to begin the thread.
java
Copy code
System.out.println("Thread is running.");
o Create a class that implements the Runnable interface and override its run() method.
java
Copy code
System.out.println("Thread is running.");
t1.start();
Inter-thread communication in Java allows threads to communicate with each other using the wait(),
notify(), and notifyAll() methods. This helps in synchronizing threads to ensure that shared resources
are accessed in a controlled manner.
Example:
java
Copy code
class SharedResource {
count++;
notify();
while (count == 0) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(e);
count--;
shared.increment();
}
});
shared.decrement();
});
t1.start();
t2.start();
In this example, one thread increments and another decrements the value of count. The wait() and
notify() methods are used to coordinate these threads.
Auto-boxing is the automatic conversion of a primitive type to its corresponding wrapper class.
Unboxing is the reverse process where the wrapper class object is converted to its primitive type.
Example:
java
Copy code
// Auto-boxing
// Unboxing
Here, int is automatically converted to Integer (auto-boxing), and Integer is converted back to int
(unboxing).
5. Java Program for Automatic Conversion (Wrapper Class to Primitive) and Unboxing
java
Copy code
// Auto-boxing
// Unboxing
6. Synchronization in Java
Synchronization is used to control access to shared resources by multiple threads to avoid data
inconsistency.
Example:
java
Copy code
class Counter {
return count;
counter.increment();
});
counter.increment();
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
System.out.println(e);
Here, the increment() method is synchronized to ensure only one thread can access it at a time.
java
Copy code
ThreadExample() {
super("My Thread");
t.start();
In this example, the super() constructor is used to call the parent class constructor (Thread), and the
child thread executes concurrently.
• byte → Byte
• short → Short
• int → Integer
• long → Long
• float → Float
• double → Double
• char → Character
• boolean → Boolean
9. Need of Synchronization
• Prevent data corruption and avoid unexpected behaviors by ensuring only one thread can
access a resource at a time.
Example:
java
Copy code
enum Day {
// Using values()
System.out.println(day);
}
// Using valueOf()
Day d = Day.valueOf("MONDAY");
Here, values() lists all enum constants, and valueOf() converts a string into the corresponding enum
constant.