Java Unit-3
Java Unit-3
Java Unit-3
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
public MyException(String s)
super(s);
}
public class Main {
// Driver Program
try {
System.out.println("Caught");
System.out.println(ex.getMessage());
1. Process-based Multitasking
2. Thread-based Multitasking
import java.io.*;
System.out.print("Welcome to GeeksforGeeks.");
Output
Welcome to GeeksforGeeks.
Example 2: By implementing Runnable interface
Java
import java.io.*;
class GFG implements Runnable {
t.start();
System.out.println(t.getName());
public final int getPriority(): The java.lang.Thread.getPriority() method returns the priority of the
given thread.
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.*;
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
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.
Types of Synchronization
There are two types of synchronization
1. Process Synchronization
2. 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. 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.
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.