Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views15 pages

javaans

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 15

1.

Define an Exception and Key Terms in Exception Handling

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.

Key Terms in Exception Handling:

• Exception: An object representing an error or event that can be handled by the program.
Example: ArithmeticException.

• Throw: Used to explicitly throw an exception in code. Example: throw new


ArithmeticException("Division by zero");.

• 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) {

System.out.println("Error: " + e.getMessage());

} finally {

System.out.println("This will always be executed.");

2. Java Program for User-Defined Exception Handling

A user-defined exception is a custom exception class that extends the Exception class.

Example:

java

Copy code

class InsufficientBalanceException extends Exception {


public InsufficientBalanceException(String message) {

super(message);

public class UserDefinedException {

public static void main(String[] args) {

try {

withdraw(1000, 2000);

} catch (InsufficientBalanceException e) {

System.out.println(e.getMessage());

static void withdraw(int balance, int amount) throws InsufficientBalanceException {

if (amount > balance) {

throw new InsufficientBalanceException("Insufficient balance to withdraw " + amount);

} else {

System.out.println("Withdrawal successful!");

3. Built-In Exception and Uncaught Exception

• Built-in Exception: These are pre-defined exceptions in Java, part of the java.lang package.
Examples include NullPointerException, IOException, ArithmeticException, etc.

• Uncaught Exception: An uncaught exception is an exception that occurs in a program but is


not caught or handled by any try-catch block. If not handled, it causes the program to
terminate. Example:

java

Copy code

public class UncaughtExceptionExample {


public static void main(String[] args) {

int result = 10 / 0; // This will throw ArithmeticException

In the above example, if there's no try-catch block, it will terminate the program with an uncaught
exception.

4. Chained Exception Handling

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

public class ChainedException {

public static void main(String[] args) {

try {

try {

throw new ArithmeticException("Inner exception");

} catch (ArithmeticException e) {

throw new NullPointerException("Outer exception").initCause(e);

} catch (NullPointerException e) {

System.out.println("Caught Exception: " + e);

System.out.println("Cause: " + e.getCause());

In this example, the NullPointerException is caused by the ArithmeticException, and you can track it
using getCause().

5. Program Throwing IllegalAccessException

The IllegalAccessException is thrown when a method or field is accessed without permission.


Example:

java

Copy code

public class IllegalAccessExample {

public static void main(String[] args) {

try {

throwIllegalAccess();

} catch (IllegalAccessException e) {

System.out.println("Exception: " + e.getMessage());

static void throwIllegalAccess() throws IllegalAccessException {

throw new IllegalAccessException("Illegal access to this method!");

In this program, the method throwIllegalAccess() throws an IllegalAccessException, and it is caught


and printed in the catch block.

6. Custom Exception for Banking Application (Withdraw with Insufficient Balance)

In this example, a custom exception InsufficientBalanceException is thrown if the balance is less than
the minimum required balance.

Example:

java

Copy code

class InsufficientBalanceException extends Exception {

public InsufficientBalanceException(String message) {

super(message);

class BankAccount {
private double balance;

private static final double MIN_BALANCE = 500;

public BankAccount(double initialBalance) {

this.balance = initialBalance;

public void withdraw(double amount) throws InsufficientBalanceException {

if (balance - amount < MIN_BALANCE) {

throw new InsufficientBalanceException("Cannot withdraw, balance below minimum required


balance.");

balance -= amount;

System.out.println("Withdrawal successful! New balance: " + balance);

public class BankingApplication {

public static void main(String[] args) {

BankAccount account = new BankAccount(1000);

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.

2. Built-In Exception: Pre-defined exceptions like NullPointerException, ArithmeticException,


etc.

3. Chained Exception: Exceptions linked together to track the cause of an error.

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.

Example of Multiple Threads in Java:

java

Copy code

class MyThread extends Thread {

public void run() {

System.out.println(Thread.currentThread().getId() + " is executing the thread.");

public class MultiThreadExample {

public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

MyThread t3 = new MyThread();

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.

Ways to Create Threads:

1. Extending the Thread Class:

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

class MyThread extends Thread {

public void run() {

System.out.println("Thread is running.");

2. Implementing the Runnable Interface:

o Create a class that implements the Runnable interface and override its run() method.

o Pass an instance of this class to a Thread object and call start().

java

Copy code

class MyRunnable implements Runnable {

public void run() {

System.out.println("Thread is running.");

public class ThreadExample {

public static void main(String[] args) {

Thread t1 = new Thread(new MyRunnable());

t1.start();

3. Inter-Thread Communication in JAVA

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 {

private int count = 0;

public synchronized void increment() {

count++;

System.out.println("Incremented: " + count);

notify();

public synchronized void decrement() {

while (count == 0) {

try {

wait();

} catch (InterruptedException e) {

System.out.println(e);

count--;

System.out.println("Decremented: " + count);

public class ThreadCommunication {

public static void main(String[] args) {

SharedResource shared = new SharedResource();

Thread t1 = new Thread(() -> {

for (int i = 0; i < 5; i++) {

shared.increment();

}
});

Thread t2 = new Thread(() -> {

for (int i = 0; i < 5; i++) {

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.

4. Auto-Boxing and Unboxing in Java

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

public class BoxingUnboxingExample {

public static void main(String[] args) {

// Auto-boxing

int num = 10;

Integer obj = num; // primitive int to Integer

// Unboxing

int val = obj; // Integer to primitive int

System.out.println("Auto-boxed value: " + obj);

System.out.println("Unboxed value: " + val);


}

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

public class WrapperToPrimitive {

public static void main(String[] args) {

// Auto-boxing

Integer obj = 100; // Integer object

// Unboxing

int num = obj; // Convert Integer to int

System.out.println("Wrapper Object: " + obj);

System.out.println("Primitive Value: " + num);

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 {

private int count = 0;

// Synchronized method to ensure only one thread can access it at a time

public synchronized void increment() {


count++;

public int getCount() {

return count;

public class SynchronizationExample {

public static void main(String[] args) {

Counter counter = new Counter();

Thread t1 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

counter.increment();

});

Thread t2 = new Thread(() -> {

for (int i = 0; i < 1000; i++) {

counter.increment();

});

t1.start();

t2.start();

try {

t1.join();

t2.join();

} catch (InterruptedException e) {
System.out.println(e);

System.out.println("Final count: " + counter.getCount());

Here, the increment() method is synchronized to ensure only one thread can access it at a time.

7. Java Program for myThread Class Using super

java

Copy code

class ThreadExample extends Thread {

ThreadExample() {

// Calling the parent class constructor

super("My Thread");

System.out.println("Thread name: " + Thread.currentThread().getName());

public void run() {

System.out.println("Child thread is running.");

public static void main(String[] args) {

ThreadExample t = new ThreadExample();

t.start();

In this example, the super() constructor is used to call the parent class constructor (Thread), and the
child thread executes concurrently.

8. Type Wrappers Supported in JAVA


Java provides wrapper classes for primitive types to allow them to be treated as objects.

• byte → Byte

• short → Short

• int → Integer

• long → Long

• float → Float

• double → Double

• char → Character

• boolean → Boolean

9. Need of Synchronization

Synchronization is needed to:

• Ensure data consistency when multiple threads access shared resources.

• Prevent data corruption and avoid unexpected behaviors by ensuring only one thread can
access a resource at a time.

10. values() and valueOf() Methods in Enumerations

• values(): Returns an array of all constants in the enum.

• valueOf(): Returns the enum constant for a given string name.

Example:

java

Copy code

enum Day {

MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;

public class EnumExample {

public static void main(String[] args) {

// Using values()

for (Day day : Day.values()) {

System.out.println(day);
}

// Using valueOf()

Day d = Day.valueOf("MONDAY");

System.out.println("Selected Day: " + d);

Here, values() lists all enum constants, and valueOf() converts a string into the corresponding enum
constant.

You might also like