Java Unit-3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

Unit 3:

1. Explain Exception handling in details


A) In Java, Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the
program’s instructions. Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is
called the exception object. It contains information about the exception, such as the
name and description of the exception and the state of the program when the
exception occurred.
Major reasons why an exception Occurs
 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out-of-disk memory)
 Code errors
 Opening an unavailable file
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running out
of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion,
etc. Errors are usually beyond the control of the programmer, and we should not try to
handle errors.

Java Exception Hierarchy

Types of Exceptions
Java defines several types of exceptions that relate to its various class libraries. Java also
allows users to define their own exceptions.
Exceptions can be categorized in two ways:
1. Built-in Exceptions
 Checked Exception
 Unchecked Exception
2. User-Defined Exceptions
Let us discuss the above-defined listed exception that is as follows:
1. 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. In simple
words, if a program throws an unchecked exception, and even if we didn’t handle or
declare it, the program would not give a compilation error.
Note: For checked vs unchecked exception, see Checked vs Unchecked Exceptions
2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In
such cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types

2. Explain – try, catch, multiple catch, throw, throws, finally ?


. Exception is an unexpected event, that occurs during the execution of a
program, i.e. at run time, which disrupts the normal flow of the program.
Exception Handling is an effective way to handle exceptions so that the regular
flow of the execution is not disturbed. When an exception occurs, an object
(exception) representing this error is created and thrown in the method that
caused it. The exception is caught and processed. 1. The "try" keyword is used to
specify a block where we should place an exception code. It means we can't use
try block alone. The try block must be followed by either catch or finally. 2. The
"catch" block is used to handle the exception. It must be preceded by a try block
which means we can't use a catch block alone. It can be followed by finally block
later. 3. The "finally" block is executed whether an exception is handled or not. It
is an optional part. It provides a mechanism for cleaning 4. The "throw" keyword
is used to throw an exception. It allows users to create and throw exceptions i.e.,
user-defined exceptions. 5. The "throws" keyword is used to inform the calling
method that the method may throw certain exceptions. It doesn't throw an
exception. It is always used with the method signature. 6. Multiple Catch Blocks -
The "try" block can be followed by multiple "catch" blocks, each catch block will
handle a different type of exception. This will allow us to provide specific handling
implementation for various exception scenarios. EX:-
try{
Int b=1/0;
}
catch(Exception e){
System.out.println(“Div by 0 not possible”);
}
finally{
System.out.println(“Executed try catch finally”);
}
3. Difference between checked and unchecked exception
4. User define exception handling and also write your own exception
subclasses
A) User defined exception handling in Java refers to the process of creating
custom exceptions to handle specific error conditions in a program. This
allows developers to define their own exception classes and throw them
when certain conditions are met, providing more specific and informative
error messages.

Certainly! Here's a simplified explanation of user-defined exception handling:

1. Define Custom Exception Class:


 You create a new class that extends the language's built-in exception class (like
Exception in Java or Python).
 This new class represents a specific type of error that you want to handle uniquely in
your program.
2. Throw Custom Exceptions:
 In your code, when a specific error condition occurs that isn't adequately represented
by built-in exceptions, you throw your custom exception using the throw keyword.
 This signals that an exceptional situation has occurred and the program should
handle it accordingly.
3. Catch Custom Exceptions:
 Surround the code where the custom exception might be thrown with a try-catch
block.
 In the catch block, specify the type of custom exception you expect to handle and
define how the program should respond to it.
4. Handle Custom Exceptions:
 Inside the catch block, implement the logic to handle the exception appropriately.
 This could involve logging the error, notifying the user, or taking corrective action to
recover from the error condition.
EXAMPLE

class MyException extends Exception {

public MyException(String s)

// Call constructor of parent Exception

super(s);

}
public class Main {

// Driver Program

public static void main(String args[])

try {

// Throw an object of user defined exception

throw new MyException("GeeksGeeks");

catch (MyException ex) {

System.out.println("Caught");

// Print the message from MyException object

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

5. Difference between thread-based multithreading and process based


multitasking
A)

Multitasking Programming has Two Types:

1. Process-based Multitasking
2. Thread-based Multitasking

6. Thread state (java thread model)


7.
7)Different ways to create the thread. Explain with program ?

A) Thread can be referred to as a lightweight process. Thread uses fewer resources to


create and exist in the process; thread shares process resources. The main thread
of Java is the thread that is started when the program starts. The slave thread is
created as a result of the main thread. This is the last thread to complete execution.
A thread can programmatically be created by:
1. Implementing the java.lang.Runnable interface.
2. Extending the java.lang.Thread class.
You can create threads by implementing the runnable interface and overriding the run()
method. Then, you can create a thread object and call the start() method.
Thread Class:
The Thread class provides constructors and methods for creating and operating on
threads. The thread extends the Object and implements the Runnable interface.
// start a newly created thread.
// Thread moves from new state to runnable state
// When it gets a chance, executes the target run() method
public void start()
Runnable interface:
Any class with instances that are intended to be executed by a thread should implement
the Runnable interface. The Runnable interface has only one method, which is called
run().
// Thread action is performed
public void run()
Benefits of creating threads :
 When compared to processes, Java Threads are more lightweight; it takes less time
and resources to create a thread.
 Threads share the data and code of their parent process.
 Thread communication is simpler than process communication.
 Context switching between threads is usually cheaper than switching between
processes.
Calling run() instead of start()
The common mistake is starting a thread using run() instead of start() method.
Thread myThread = new Thread(MyRunnable());
myThread.run(); //should be start();
The run() method is not called by the thread you created. Instead, it is called by the thread
that created the myThread.
Example 1: By using Thread Class
 Java

import java.io.*;

class GFG extends Thread {

public void run()

System.out.print("Welcome to GeeksforGeeks.");

public static void main(String[] args)

GFG g = new GFG(); // creating thread

g.start(); // starting thread

Output
Welcome to GeeksforGeeks.
Example 2: By implementing Runnable interface
 Java

import java.io.*;
class GFG implements Runnable {

public static void main(String args[])

// create an object of Runnable target

GFG gfg = new GFG();

// pass the runnable reference to Thread

Thread t = new Thread(gfg, "gfg");

// start the thread

t.start();

// get the name of the thread

System.out.println(t.getName());

@Override public void run()

System.out.println("Inside run method");

8)Different thread methods and explain thread priorities ?


A) Priority of a Thread (Thread Priority)
Each thread has a priority. Priorities are represented by a number between 1 and 10. In most cases,
the thread scheduler schedules the threads according to their priority (known as preemptive
scheduling). But it is not guaranteed because it depends on JVM specification that which scheduling
it chooses. Note that not only JVM a Java programmer can also assign the priorities of a thread
explicitly in a Java program.
Setter & Getter Method of Thread Priority
Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the
given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or


assign the priority of the thread to newPriority. The method throws IllegalArgumentException if the
value newPriority goes out of the range, which is 1 (minimum) to 10 (maximum).

3 constants defined in Thread class:


1. public static int MIN_PRIORITY

2. public static int NORM_PRIORITY

3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.

import java.lang.*;

class ThreadDemo extends Thread {


public void run() {
System.out.println("Inside run method");
}

public static void main(String[] args) {


ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();

System.out.println("t1 thread priority : " + t1.getPriority());


System.out.println("t2 thread priority : " + t2.getPriority());
System.out.println("t3 thread priority : " + t3.getPriority());

t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);

System.out.println("t1 thread priority : " + t1.getPriority());


System.out.println("t2 thread priority : " + t2.getPriority());
System.out.println("t3 thread priority : " + t3.getPriority());

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


System.out.println("Main thread priority : " + Thread.currentThread().getPriority());

Thread.currentThread().setPriority(10);
System.out.println("Main thread priority : " + Thread.currentThread().getPriority());
}
}
Out put
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10

9.Thread Synchronization ?
Synchronization in Java
Synchronization in Java is the capability to control the access of multiple threads to any
shared resource.

Java Synchronization is better option where we want to allow only one thread to access the
shared resource.

Why use Synchronization?


The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing data. It
can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every object
has a lock associated with it. By convention, a thread that needs consistent access to an
object's fields has to acquire the object's lock before accessing them, and then release the
lock when it's done with them.

From Java 5 the package java.util.concurrent.locks contains several lock implementations.

10.Inter Thread communication (producer- consumer problem)


11.Serialization, Enumeration, Autoboxing and generics
A)
Certainly! Let's discuss each of these concepts briefly:

1. Serialization:
 Serialization is the process of converting an object into a stream of bytes so that it
can be easily stored, transmitted over a network, or persisted to disk.
 In Java, serialization is achieved by implementing the Serializable interface, which
marks a class as serializable.
 Serialization allows objects to be saved and reconstructed later, preserving their state.
 It's commonly used in scenarios like saving object state in files, sending objects over
the network, or storing objects in databases.
2. Enumeration:
 Enumeration is a concept used to represent a fixed set of values or constants.
 In Java, the Enum type is used to define enumerations.
 Enumerations can contain a fixed number of predefined values, each of which
represents a specific constant.
 Enumerations provide type safety and readability in code, making it clear which values
are acceptable for a particular variable or parameter.
3. Autoboxing:
 Autoboxing is the automatic conversion of primitive data types to their corresponding
wrapper classes and vice versa.
 In Java, primitive data types like int, float, double, etc., have corresponding wrapper
classes like Integer, Float, Double, etc.
 Autoboxing allows you to seamlessly switch between primitive types and their
wrapper classes without explicit conversion, making code more concise and readable.
For example, autoboxing allows you to assign an int value to an Integer object
without explicitly calling new Integer(int).
4. Generics:
 Generics introduce parameterized types in Java, allowing classes and methods to
operate on objects of specified types.
 Generics provide compile-time type safety by allowing you to specify the type of
objects that a collection or class can contain or operate on.
 They enable you to write reusable and type-safe code without resorting to casting.
 Generics are commonly used with collections like ArrayList, HashMap, etc., to specify
the type of elements they can hold.
 They also enable the creation of generic classes and methods, which can operate on
objects of any type specified by the caller.

Each of these concepts plays a crucial role in Java programming, providing powerful features
for data manipulation, type safety, and code organization.

12.Explore java.util package

A) The java.util package in Java provides a wide range of utility classes and interfaces to
facilitate various common tasks such as working with collections, dates, times, and more.
Here are some key components of the java.util package:

1. Collections Framework:
 The Collections Framework provides a set of interfaces and classes to represent and
manipulate collections of objects, such as lists, sets, and maps.
 Some important classes and interfaces in the Collections Framework include List,
Set, Map, ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, etc.
 It offers algorithms for sorting, searching, and manipulating collections.
2. Date and Time API:
 The java.util package includes classes like Date, Calendar, and TimeZone for
working with dates and times. However, these classes have been largely supplanted
by the newer Date and Time API introduced in Java 8.
 The Date and Time API, located in the java.time package, provides classes like
LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Duration, Period, etc., for
handling dates, times, and time zones in a more modern and comprehensive way.
3. Random Numbers:
 The Random class provides methods for generating random numbers of different
types.
 It is commonly used in simulations, games, and cryptographic applications.
4. Scanner:
 The Scanner class provides methods for parsing input streams into tokens of various
types, such as integers, floats, strings, etc.
 It is commonly used for reading user input from the console or parsing text files.
5. UUID:
 The UUID class provides methods for generating universally unique identifiers (UUIDs).
 UUIDs are 128-bit unique identifiers that are commonly used in distributed systems
and for generating unique identifiers for objects.
6. Miscellaneous Utilities:
 The java.util package also includes various utility classes and interfaces for tasks
like handling properties ( Properties), performing basic operations on objects
(Objects), handling string manipulation ( StringTokenizer), etc.

These are just some of the many classes and interfaces available in the java.util package.
It is one of the core utility packages in Java and is frequently used in Java applications for a
wide range of tasks.

You might also like