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

JAVA UNIT4

The document covers Java packages and libraries, detailing how to define and import packages, as well as access control and the Java.lang package. It also explains exception handling in Java, including types of exceptions, keywords used for handling exceptions, and the structure of try-catch blocks. Additionally, it discusses custom exceptions, the hierarchy of standard exceptions, and various utility classes in Java, such as Math and wrapper classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

JAVA UNIT4

The document covers Java packages and libraries, detailing how to define and import packages, as well as access control and the Java.lang package. It also explains exception handling in Java, including types of exceptions, keywords used for handling exceptions, and the structure of try-catch blocks. Additionally, it discusses custom exceptions, the hierarchy of standard exceptions, and various utility classes in Java, such as Math and wrapper classes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT-4

Packages and Java Library: Introduction, Defining Package, Importing Packages and Classes
into Programs, Path and Class Path, Access Control, Packages in Java SE, Java.lang Package
and its Classes, Class Object, Enumeration, class Math, Wrapper Classes, Auto-boxing and
Auto-unboxing, Java util Classes and Interfaces, Formatter Class, Random Class, Time
Package, Class Instant (java.time.Instant), Formatting for Date/Time in Java, Temporal
Adjusters Class.
Exception Handling: Introduction, Hierarchy of Standard Exception Classes, Keywords
throws and throw, try, catch, and finally Blocks, Multiple Catch Clauses, Class Throwable,
Unchecked Exceptions, Checked Exceptions, try-with-resources, Catching Subclass Exception,
Custom Exceptions, Nested try and catch Blocks, Rethrowing Exception, Throws Clause.

Concept-1 Exception Handling: Introduction

 The Exception Handling in Java is one of the powerful mechanisms to handle the runtime
errors so that normal flow of the application can be maintained.
 In other words, an exception is a run-time error. Exception is an abnormal condition.
 In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.
 Exceptions can be generated by the Java run-time system, or they can be manually generated
by your code.
 Java exception handling is managed via five keywords:
try, catch, and finally, throw, throws
 Program statements that you want to monitor for exceptions are contained within a try block.
 If an exception occurs within the try block, it is thrown. Your code can catch this exception
(using catch) and handle it in some rational manner.
 System-generated exceptions are automatically thrown by the Java run-time system.
 An exception can occur for many different reasons.
 Following are some scenarios where an exception occurs.

1. A user has entered an invalid data.


2. A file that needs to be opened cannot be found.
3. A network connection has been lost in the middle of communications or the JVM
has run out of memory.
Advantage of Exception Handling
 The core advantage of exception handling is to maintain the normal flow of the application.
 An exception normally disrupts the normal flow of the application that is why we use
exception handling.
Uncaught Exceptions Java run-time system detects the attempt to divide by zero. The
execution of Exc0 to stop, because once an exception has been
thrown, it must be caught by an exception handler and deal with
immediately.

Output:-

The exception is caught by the default handler provided by the Java run-time system. Any exception
that is not caught by your program will ultimately be processed by the default handler. The default
handler displays a string describing the exception and terminates the program.

Concept-2 Types of Java Exceptions


 There are mainly two types of exceptions: checked and unchecked.
Checked exceptions:- A checked exception is an exception that is checked by the compiler at
compilation- time, these are also called as compile time exceptions. These exceptions cannot
simply be ignored, the programmer should take care of (handle) these exceptions.
For Example:- ClassNotFoundException, NoSuchFieldException,
NoSuchMethodException etc;
Unchecked exceptions:- An unchecked exception is an exception that occurs at the time of
execution. These are also called as Runtime Exceptions. These include programming bugs,
such as logic errors or improper use of an API. Runtime exceptions are ignored at
the time of compilation.
For Example:- ArithmeticException, ArrayIndexOutOfBoundsException,
NullPointerException, NegativeArraySizeException etc;
Unchecked Subclasses

Checked Subclasses
Concept-3 Keywords throws and throw, try, catch, and finally Blocks
Syntax
Here, ExceptionType is the type of exception that has
occurred

try block
 To handle an exception yourself it provides two benefits First, it allows you to fix the error.
Second, it prevents the program from automatically terminating.
 It handle a run-time error, simply enclose the code that you want to monitor inside a try
block Immediately following the try block, include a catch clause that specifies the exception
type that you wish to catch. Java try block must be followed by either catch or finally
block.
catch block/clause
 Java catch block is used to handle the Exception by declaring the type of exception within
the parameter. The declared exception must be the parent class exception (i.e., Exception)
OR the generated exception type. The catch block must be used after the try block only.
You can use multiple catch block with a single try block.
Program: Output

finally block:

 Java finally block is a block that is used to execute important code such as closing
connection, stream etc. Java finally block is always executed whether exception is handled or
not. Java finally block follows try or catch block. The finally clause is optional.

 Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.
Program
Output:

throw
 The throw keyword is used to explicitly throw a single exception.
 The keyword throw is used to throw an exception objects within a method.
 We can throw either checked or unchecked exception in java by throw keyword.
Syntax:- throw exceptionobject;
 We use the throw keyword within a method.
Program

Output:-

throws (OR) Throws Clause


 The throws keyword in Java is used to declare exceptions that can occur during the execution
of a program.
 For any method that can throw exceptions, it is mandatory to use the throws keyword to list
the exceptions that can be thrown.
 The throws keyword provides information about the exceptions to the programmer as well as
to the caller of the method that throws the exceptions.
Syntax:

Program:

Concept-4 Multiple Catch Clauses


 More than one exception could be raised by a single piece of code. To handle this type of
situation, you can specify two or more catch clauses, each catching a different type of
exception.
 When an exception is thrown, each catch statement is inspected in order, and the first one
whose type matches that of the exception is executed.
 After one catch statement executes, the others are bypassed, and execution continues after
the try/catch block.
Program:

Output:

Concept-5 Hierarchy of Standard Exception


 In Java, exceptions are objects of a classes derived from the class Throwable which is derived
from class Object.
 Whenever an exception is thrown, it implies that an exception object is thrown.
 The next level of derived classes comprises two classes: the class Error and class Exception.
 Error class involves errors that are mainly caused by the environment in which an application
is running.
 All errors in Java happen during runtime.
 It is not possible to recover from an error using try–catch blocks.
Examples:
 OutOfMemoryError occurs when the JVM runs out of memory and StackOverflowError
occurs when the stack overflows.
 The Error class includes such errors over which a programmer has less control.
 A programmer cannot do anything about these errors except to get the error message and
check the program code.
 Exception class represents exceptions that are mainly caused by the application itself.
 The only option available is to terminate the execution of the program and recover from
exceptions using either the try–catch block or throwing an exception.
 A programmer can have control over the exceptions defined by several subclasses of class
Exception.
 The subclasses of Exception class are broadly subdivided into two categories.
 Unchecked exceptions These are subclasses of class RuntimeException, derived from
Exception class. For these exceptions, the compiler does not check whether the method that
throws these exceptions has provided any exception handler code or not.
 Checked exceptions These are direct subclasses of the Exception class and are not subclasses
of the class RuntimeException. These are called so because the compiler ensures (checks) that
the methods that throw checked exceptions deal with them.
Concept-6 try-with-resources
 The Resources such as file, database, or Internet connections that are opened in try block are
closed in finally block, which is always executed.
 The try-with-resources statement automatically closes all the resources at the end of the
statement.
 A resource is an object to be closed at the end of the program.
Syntax
 Java 7 has added AutoCloseable interface and along with it another try block called try-with-
resources. AutoCloseable interface has one methods close().
 The method close() is invokes automatically on sources that implement the interface and are
managed by try-with-resources.
Program:

Concept-7 Nested try and catch Blocks


 The try block within a try block is known as nested try block in java.
 Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.
 If no catch block matches, then the Java runtime system handles the exception.
Program: Output:

Concept:-8 Catching Subclass Exception


 A method in super class. When this method is overridden in subclass with exception handling,
then there are some points that need to be taken into consideration.
 If the super class method does not declare any exception, then subclass overridden method
cannot declare checked exceptions but it can declared unchecked exceptions.
Program: Subclass overridden method declaring checked exception
Output:

Program: Subclass overridden method declaring unchecked exception

Output:
Concept:-9 Custom Exceptions
 It is also called as user defined exception.
 A programmer may create his/her own exception class by extending the exception class and
can customize the exception according to his/her needs.
 Using Java custom exception, the programmer can write their own exceptions and messages.
Step to Follows
1. Extend the Exception class as
class UserException extends Exception
{
// Statements
}
2. Define constructor of user exception class and this constructor takes a string argument.
The public Exception( String message) construct a new exception with the given detailed
message.
3. Write the code for the class containing the main class. The try catch block is written within
this class.
Program:

Output:
Concept:-10 Rethrowing Exception
 When an exception is cached in a catch block, you can re-throw it using the throw keyword
(which is used to throw the exception objects).
Program:

Output:
Concept:-11 Introduction, Defining Package
 A java package is a group of similar types of classes, interfaces and sub-packages.
 A Package can be defined as a collection used for grouping a variety of classes and interface
based on their functionality
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection & removes naming collision.
 This means that a unique name had to be used for each class to avoid name collision
 Package in java can be categorized in two form, built-in package or API and user-defined
package.
 There are many built-in packages such as java, lang, net, io, util, sql etc.
 The related classes are put the into one packages.
 After that, we can simply write an import statement from existing packages and use it in our
program.
 A package is a container of a group of related classes.

Built-in Packages
These packages consist of a large number of classes which are a part of Java API. Some of the
commonly used built-in packages are:
1) java.lang: Contains language support classes (e.g classes which defines primitive
data types, math operations). This package is automatically imported.
2) java.io: Contains classes for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support; for Date / Time operations.
4) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user.
 A package declaration resides at the top of a java source file. All class are to be placed in a
package have common package name.
 The name of the package should be followed by the keyword package, declared at the top of
the program. Thus, we can define a class belonging to a package.
Syntax of package
package <package_name>
Example of package package Ramachandra;
 While declaring the package every character must be in lower case.
 The source file allow to declared only one package and it must be the first statement in a
JAVA source file
 The Package statement defines a name space in which classes are stored.
 If omit the package statement, the class name are put into the default package, which has no
name.
Concept:-12 Importing Packages and Classes into Programs
How to access package from another package?
There are three ways to access the package from outside the package.
1) import package.*;
2) import package.classname;
3) fully qualified name.
1) import package.*;
 If you use package.* then all the classes and interfaces of this package will be accessible.
 The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*

2) import package.classname;
 If you import package.classname then only declared class of this package will be accessible.
Example of package by import package.classname
3) fully qualified name.
 If you use fully qualified name then only declared class of this package will be accessible.
 Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.
 It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example of package by import fully qualified name

Concept:-13 Wrapper Classes and Auto-boxing and Auto-unboxing


 The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.
 The wrapper classes in Java are used to convert primitive types (int, char, float, etc) into
corresponding objects.
 Autoboxing and Unboxing are the features included in Java 1.5
 Autoboxing and Unboxing feature convert primitives into objects and objects into primitives
automatically.
 The automatic conversion of primitive into object is known as Autoboxing and vice-versa
Unboxing.
Auto Boxing or Boxing:
1. Autoboxing is the process of converting a primitive type data into its corresponding wrapper
class object instance
2. Done dynamically
Unboxing:
1. Unboxing is the process of converting a wrapper instance into a primitive type
2. Done automatically

 The eight classes of java.lang package are known as wrapper classes in java.
Methods of Wrapper Classes
1. equals()
2. byteValue()
3. compareTo(type Object)
4. doubleValue()
5. floatValue()
6. intValue()
7. longValue()
8. ShortValue()
9. toHexString(type number)
10. valueOf(type number)
11. valueOf(String str)
12. toString(type number)
Program:

Concept:-14 class Math


 Java Math Class in Java contains certain methods to perform different numeric operations, is
exponential, square root, logarithmic, trigonometric functions.
 Java Math class provides several methods to work on math calculations like min(),
max(),avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
 Arithmetic operations like increment, decrement, divide, absolute value, It should be checked
against the maximum and minimum value as appropriate.
Methods in Math Class

Method Description
Math.abs() It will return the Absolute value of the given value.
Math.max() It returns the Largest of two values.
Math.min() It is used to return the Smallest of two values.
Math.round() It is used to round of the decimal numbers to the nearest value.
Math.sqrt() It is used to return the square root of a number.
Math.cbrt() It is used to return the cube root of a number.
Math.pow() It returns the value of first argument raised to the power to second argument
It is used to find the largest integer value which is less than or equal to the
Math.floor()
argument and is equal to the mathematical integer of a double value.
It is used to find the smallest integer value that is greater than or equal to the
Math.ceil()
argument or mathematical integer.
Math.sin() It is used to return the trigonometric Sine value of a Given double value.
Math.cos() It is used to return the trigonometric Cosine value of a Given double value.
Math.tan() It is used to return the trigonometric Tangent value of a Given double value.
Program
Output:

Concept:-15 Java.lang Package and its Classes


 The java.lang package is one of the core packages in the Java programming language.
 It contains fundamental classes and interfaces that are automatically imported into every
Java program, making them readily available without the need for explicit imports.
Classes of java.lang Package
Class name Description
Object Super class to all other classes in JAVA
Package For managing packages
Math Contains several mathematical Methods
Subclass of object, it defines methods for
String, Stringbuffer, StringBuilder
handling strings
Thread Supports creation of new threads of execution
Enum Defines methods that support enumeration
Boolean, Byte, Character, Float, Integer, Wrapper class to provide reference to the
Short, Long, Double corresponding type
Interface of java.lang Package
Interface name Description

Appendable Define methods for appending a character


CharSequence Define a method for granting read only access to sequence of characters
Comparable Define method compareTo() for ordering objects
Readable Define method for reading character into buffer
Runnable Define a method void run(), Implemented by class that creates new threads
Concept:-16 Enumeration
 The Enum in Java is a data type which contains a fixed set of constants.
 It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) etc.
 According to the Java naming conventions, we should have all constants in capital letters.
So, we have enum constants in capital letters.
 Enums are used to create our own data type like classes. The enum data type (also known
as Enumerated Data Type).
 we can define an enum either inside the class or outside the class.
Methods of Enumeration class
public static type_enum valueof(String str); This method returns the value of given constant
enum.
public static type_enum[] values(); This method returns an array containing all the values of
the enum.
public static int ordinal(); This method returns the index of the enum value.

Program
Output:-
Concept:-17 Java util Classes and Interfaces

Concept:-18 Formatter Class


 The class Formatter supports the formatting of the output of characters, strings, and numeric
types.
 The declaration of this class is highly inspired by the printf method of C programming
language
 Class Formatter provides support for layout justification, alignment, formats for numeric,
string, and date/time data.
 The format string for output of numeric values comprises a % sign followed by a conversion
character.
 The field width and precision are specified between the % sign and the conversion character
Program
Concept:-19 Random Class
 Random class is part of java.util package.
 Random class is used to generate random numbers.
 This class provides several methods to generate random numbers of type int, double, float,
long, float etc.
Constructors
 Random() : creates a new random generator with seed number provided by the system.
 Random(long seed): creates a random generator with seed number suppiled by the use.
Seed number is an integer that sets the starting point for generating random number.
Methods in Random class
nextBoolean() : which returns random Boolean values

nextDouble() : which returns random double values from 0 to 1.0

nextfloat(): which returns random float values from 0 to 1.0

nextInt() : which returns random integer values

nextInt(int n): returns random values between 0 and specified number

Program Output
Concept:-20 Time package
 This package is used for all the date, time related operations. The various classes in this
package are.
Clock: Provides access to current date, time according to the zone specified.
Duration: It is the amount of time spent/recorded etc.
LocalDate: It is a date without any specified time zone.
LocalDateTime: It is a date-time without a time zone.
LocalTime: It represents a time without a time zone.
Monthday: It represents a day of the month in the calendar.
Period: It represents a amount of time.
Year: It represents a year in the calendar system
YearMonth: It represents a combination of the month & the year.
Concept:-21 Formatting for Date/Time in Java 8
 The java.text.SimpleDateFormat class provides methods to format and parse date and time
in java.
 The SimpleDateFormat is a concrete class for formatting and parsing date which inherits
java.text.DateFormat class.
Note: formatting means converting date to string and parsing means converting string to date.
Output:

Concept:-22 Temporal Adjusters class


Temporal Adjuster Interface
 The java.time.temporal defines an interface by name TemporalAdjuster that defines
methods that take a temporal value and return an adjusted temporal value according to a
user's specifications.
Temporal Adjusters class
 The package also defines a class TemporalAdjusters, which contains predefined used by a
programmer. Some examples of adjusters are as follows.
i. firstDayOfMonth() ii. lastDayOfMonth() iii. firstDayOfyear()
iv. lastDayOfYear v. firstDayOfWeek () vi. lastDayOfWeek()
vii. firstInMonth (DayOfWeek. Monday) viii. lastInMonth (DayOfWeek. FRIDAY)
 All these methods are static methods
Program

Output:
Important Questions
1. Write a java program that demonstrates how certain exception types are not allowed to be
thrown.
2. Write the benefits of packages
3. What are the advantages of using an Exception handling mechanism in a program?
4. How can we add a class to a package?
5. Explain about creation and importing packages
6. Explain about access specifiers in packages.
7. Explain about the Java time package
8. Explain about wrapper classes and its methods and boxing process.
9. Explain about exception handling.
10. Define a Package and Explain about importing a class into Programs?
11. Explain class Math and Wrapper classes in java?
12. Explain about java util classes and interfaces?
13. Explain concept of Temporal adjusters’ class?
14. What is Exception? Write a java program to handle exception handling
15. Write a java program to accept multiple catch blocks in java?
16. Differences between checked exception and unchecked Exception?

You might also like