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

javaanswers3

Uploaded by

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

javaanswers3

Uploaded by

secretoperato
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

1. Define an exception.

Explain the key terms used in exception handling with


Examples.

An exception in Java is an event that disrupts the normal flow of the program's
execution. It typically represents an error condition or an unexpected event that
occurs during the runtime of a program, such as trying to divide by zero, accessing
an out-of-bounds array index, or attempting to open a file that doesn't exist.

Key Terms Used in Exception Handling in Java

• 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:-

import java.io.*;

public class ExceptionHandlingExample {

public static void readFile(String filename) throws FileNotFoundException {

new FileReader(filename); // Directly try to open the file

public static void main(String[] args) {

try {

readFile("nonexistentfile.txt");

} catch (FileNotFoundException e) {

System.out.println("File not found: " + e.getMessage());

} finally {

System.out.println("This block is always executed.");

try {

int result = 10 / 0; // ArithmeticException

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero: " + e.getMessage());

}
}

Output:

File not found: nonexistentfile.txt

This block is always executed.

Cannot divide by zero: / by zero


2. Write a java program for user defined exception handling

In Java user-defined exceptions allows you to define your own exception types
that can be thrown and caught in the program.

Example Program:

java

// Define a user-defined exception called InvalidAgeException

class InvalidAgeException extends Exception {

// Constructor that accepts a message

public InvalidAgeException(String message) {

super(message);

public class UserDefinedExceptionExample {

// Method to check if the age is valid

public static void validateAge(int age) throws InvalidAgeException {

if (age < 18) {

throw new InvalidAgeException("Age must be 18 or older to proceed.");

System.out.println("Age is valid.");

}
public static void main(String[] args) {

// Sample age input (you can replace this with actual user input if desired)

int age = 16;

try {

// Validate the age

validateAge(age);

} catch (InvalidAgeException e) {

// Handle the exception (print the error message)

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

// Continue with the rest of the program

System.out.println("Program continues after exception handling.");

Output:

Error: Age must be 18 or older to proceed.

Program continues after exception handling.


3. Explain built in exception and uncaught exception

Built-in Exceptions

Built-in exceptions are the exceptions that are available in Java libraries. These
exceptions are suitable to explain certain error situations.

 Checked Exceptions: Checked exceptions are called compile-time


exceptions because these exceptions are checked at compile-time by the
compiler.

 Unchecked Exceptions: The unchecked exceptions are just opposite to the


checked exceptions. The compiler will not check these exceptions at compile
time.

Example:-

public class UncheckedExceptionExample {

public static void main(String[] args) {

int result = 10 / 0; // Unchecked exception (ArithmeticException)

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero

at UncheckedExceptionExample.main(UncheckedExceptionExample.java:3)
 An uncaught exception is an exception that is thrown but not caught by any
catch block in the program.

Uncaught Exception

public class UncaughtExceptionExample {

public static void main(String[] args) {

// The exception is uncaught

System.out.println(10 / 0); // ArithmeticException will occur

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero

at UncaughtExceptionExample.main(UncaughtExceptionExample.java:4)
4. Illustrate the mechanism of handling chained exception with an example

In Java, chained exceptions are a mechanism where one exception causes another
exception to be thrown, or where an exception is used to provide more context or
detail about another exception.

The Java Throwable class provides two methods for chaining exceptions:

1. initCause(Throwable cause): This method allows an exception to be chained


by specifying the cause of the current exception.

2. getCause(): This method retrieves the cause of the exception.

Example

import java.io.*;

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());


}

Output:-

Caught Exception: java.lang.NullPointerException: Outer exception

Cause: java.lang.ArithmeticException: Inner exception


5. Write a program that contains one method that will throw an
IllegalAccessException and use proper exception handles so that the
exception should be printed

public class IllegalAccessExceptionExample {

// Method that throws an IllegalAccessException

public static void throwIllegalAccessException() throws IllegalAccessException


{

boolean accessDenied = true;

if (accessDenied) {

throw new IllegalAccessException("Access to this resource is denied.");

public static void main(String[] args) {

try {

// Call the method that throws IllegalAccessException

throwIllegalAccessException();

} catch (IllegalAccessException e) {

// Handle the exception and print its message

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

}
}

Output:-

Caught Exception: Access to this resource is denied.


6. Write a Java program for a banking application to throw an exception
when a person tries to withdraw the amount even through he/she has lesser
than minimum balance(create custom exception)

class InsufficientBalanceException extends Exception {

public InsufficientBalanceException(String msg) {

super(msg);

class BankAccount {

private double balance;

private static final double MIN_BALANCE = 100;

public BankAccount(double balance) {

this.balance = balance;

public void withdraw(double amount) throws InsufficientBalanceException {

if (balance - amount < MIN_BALANCE)

throw new InsufficientBalanceException("Insufficient balance to maintain


minimum balance.");

balance -= amount;

public double getBalance() {


return balance;

public class BankingApplication {

public static void main(String[] args) {

BankAccount account = new BankAccount(500);

try {

account.withdraw(450);

} catch (InsufficientBalanceException e) {

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

System.out.println("Final balance: " + account.getBalance());

Output

Error: Insufficient balance to maintain minimum balance.

Final balance: 500.0


MODULE -5

7. What is multithreading? Write a program to create multiple threads in


JAVA

Multithreading is a feature of Java (and other programming languages) that


allows multiple threads (small units of a process) to run concurrently. Each thread
operates independently, which allows a program to perform multiple operations at
the same time.

EX:-

class MyThread extends Thread {

public void run() {

System.out.println(Thread.currentThread().getId() + " is running.");

public static void main(String[] args) {

MyThread t1 = new MyThread();

MyThread t2 = new MyThread();

t1.start(); // Start thread 1

t2.start(); // Start thread 2

Output:-

1 is running.
2 is running.
8. What do you mean by a thread? Explain the different ways of creating
threads.

A thread is the smallest unit of execution within a program. It represents a single


sequence of instructions that can be executed by the CPU.

1. Creating a Thread by Extending the Thread Class:

In this approach, you create a new class that extends the Thread class and overrides
the run() method to define the code to be executed by the thread.

Example:

class MyThread extends Thread {

public void run() {

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

Output Example:

Thread is running
2. Creating a Thread by Implementing the Runnable Interface:

In this approach, you create a class that implements the Runnable interface and
override its run() method. The Runnable object is then passed to a Thread object to
create a new thread.

Example:

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();

Output

Thread is running
9. Explain with an example how inter-thread communication is implemented
in JAVA

Inter-thread Communication in Java

Inter-thread communication is a technique that allows threads to communicate with


each other during the execution of a program. In Java, inter-thread communication
is implemented using the following methods provided by the Object class:

 wait(): Causes the current thread to release the lock and enter the waiting
state until it is awakened by another thread.

 notify(): Wakes up one thread that is waiting on the object's monitor.

 notifyAll(): Wakes up all threads that are waiting on the object's monitor.

Example:-

class SharedBuffer {

private int data;

private boolean isDataAvailable = false;

public synchronized void produce(int data) throws InterruptedException {

while (isDataAvailable) wait();

this.data = data;

System.out.println("Produced: " + data);


isDataAvailable = true;

notify();

public synchronized void consume() throws InterruptedException {

while (!isDataAvailable) wait();

System.out.println("Consumed: " + data);

isDataAvailable = false;

notify();

public class InterThreadCommunicationExample {

public static void main(String[] args) {

SharedBuffer buffer = new SharedBuffer();

new Thread(() -> { try { for (int i = 0; i < 5; i++) { buffer.produce(i);


Thread.sleep(1000); } } catch (InterruptedException e) {} }).start();

new Thread(() -> { try { for (int i = 0; i < 5; i++) { buffer.consume();


Thread.sleep(1500); } } catch (InterruptedException e) {} }).start();

}
Output:-

Produced: 0

Consumed: 0

Produced: 1

Consumed: 1

Produced: 2

Consumed: 2

Produced: 3

Consumed: 3

Produced: 4

Consumed: 4
10.Explain auto-boxing/unboxing occurs in expressions and operators.

Autoboxing refers to the conversion of a primitive value into an object of the


corresponding wrapper class is called autoboxing.

For example, converting int to Integer class.

Unboxing on the other hand refers to converting an object of a wrapper type to its
corresponding primitive value.

For example conversion of Integer to int.

Example:-

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);

}
Output:-

Auto-boxed value: 10

Unboxed value: 20

Here, int is automatically converted to Integer (auto-boxing), and Integer is


converted back to int (unboxing).
11.Develop a Java program for automatic conversion of wrapper class type
into corresponding primitive type and also demonstrate unboxing.

public class AutoboxingUnboxingDemo {

public static void main(String[] args) {

int intValue = 10;

double doubleValue = 20.5;

char charValue = 'A';

Integer intObject = intValue;

Double doubleObject = doubleValue;

Character charObject = charValue;

System.out.println("Autoboxed values:");

System.out.println("Integer: " + intObject + "\nDouble: " + doubleObject + "\


nCharacter: " + charObject);

System.out.println("\nUnboxed values:");

System.out.println("int: " + intObject + "\ndouble: " + doubleObject + "\


nchar: " + charObject);

System.out.println("\nUnboxing in an expression:");
System.out.println("Sum of " + intObject + " and 5 is: " + (intObject + 5));

System.out.println("\nAutoboxing in an expression:");

System.out.println("The result of intValue + 20 is: " + (intValue + 20));

Output:-

Autoboxed values:

Integer: 10

Double: 20.5

Character: A

Unboxed values:

int: 10

double: 20.5

char: A

Unboxing in an expression:

Sum of 10 and 5 is: 15


Autoboxing in an expression:

The result of intValue + 20 is: 30


12.Explain with an example how synchronization is implemented in JAVA

Synchronization in Java is a mechanism to control the access of multiple threads to


shared resources. It helps prevent data inconsistency by ensuring that only one
thread can access a shared resource at a time.

Example:-

class BankAccount {

private int balance = 1000;

synchronized void deposit(int amount) {

balance += amount;

System.out.println("Deposited " + amount + ". New Balance: " + balance);

synchronized void withdraw(int amount) {

if (balance >= amount) {

balance -= amount;

System.out.println("Withdrew " + amount + ". New Balance: " + balance);

} else {

System.out.println("Insufficient funds for withdrawal of " + amount);

}
public class SynchronizationExample {

public static void main(String[] args) {

BankAccount account = new BankAccount();

new Thread(() -> { account.deposit(500); account.withdraw(200); }).start();

new Thread(() -> { account.deposit(500); account.withdraw(200); }).start();

Output:-

Deposited 500. New Balance: 1500

Withdrew 200. New Balance: 1300

Deposited 500. New Balance: 1800

Withdrew 200. New Balance: 1600


13.Develop a Java program to create a class myThread. Call the base class
constructor in this class’s 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 child thread are executed concurrently.

package Programs;

class MyThread extends Thread {

public MyThread(String name) {

super(name);

start();

public void run() {

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

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

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}
}

public class Main { public static void main(String[] args) {

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

System.out.println("Main Thread: " + i);

try { Thread.sleep(500);

} catch (InterruptedException e) {

e.printStackTrace();

MyThread myThread = new MyThread("Child Thread");

OUTPUT:

Main Thread: 1

Main Thread: 2

Main Thread: 3

Main Thread: 4

Main Thread: 5

Child Thread: 1

Child Thread: 2
Child Thread: 3

Child Thread: 4

Child Thread: 5
14.Summarize type wrappers supported in JAVA

In Java, wrapper classes are used to represent primitive data types as objects. These
classes are part of the java.lang package and allow primitives to be treated as
objects, which is necessary in situations where you need to store primitive types in
collections (like ArrayList), work with generics, or pass values by reference.

Primitive Wrapper Class


Type

boolean Boolean

byte Byte

char Character

short Short

int Integer

long Long

float Float
double Double
15.What is the need of synchronization?

Synchronization in Java is essential for ensuring that multiple threads can safely
access shared resources, such as variables, data structures, or methods, without
causing data corruption or inconsistent results.

Here's an in-depth explanation of why synchronization is needed in Java:

1. Preventing Data Inconsistency (Race Conditions)

When multiple threads attempt to read and modify shared data simultaneously, a
race condition may occur.

2.Thread Safety

When multiple threads access a shared resource, it is crucial to ensure that only
one thread can access a critical section (a part of the code that accesses shared
data) at any given time.

3. Atomicity of Operations

Atomic operations are those that are performed as a single, indivisible unit,
meaning they cannot be interrupted or interfered with by other threads.

4. Deadlock Prevention

While synchronization helps to avoid race conditions, improper usage of


synchronization can lead to deadlocks.

6. Visibility of Shared Data

Without synchronization, changes made by one thread may not be immediately


visible to other threads.
16.Discuss values() and value Of() methods in Enumerations with suitable
examples.

In Java, Enumerations (Enums) are a special class type used to define collections
of constants. Enums were introduced in Java 5 and have several built-in methods
that make working with them more convenient. Among these methods, values()
and valueOf() are commonly used.

1.The values() method is a static method that is implicitly added by the Java
compiler to all enum types. It returns an array of the enum's constants in the
order they were declared in the enum.

Example:-

enum Day {

MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY,


SUNDAY;

public class EnumExample {

public static void main(String[] args) {

// Using values() to get all enum constants

Day[] days = Day.values();

// Iterating over the enum constants


for (Day day : days) {

System.out.println(day);

Output:-

MONDAY

TUESDAY

WEDNESDAY

THURSDAY

FRIDAY

SATURDAY

SUNDAY

The valueOf() method is another static method provided by Java for all enum
types. It is used to convert a string to its corresponding enum constant.

Example:-

enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY, SUNDAY; }

public class EnumExample {


public static void main(String[] args) {

System.out.println(Day.valueOf("MONDAY"));

try { Day.valueOf("FUNDAY"); }

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

Output:-

Selected Day: WEDNESDAY

WEDNESDAY

THURSDAY

FRIDAY

SATURDAY

SUNDAY

You might also like