JAVA UNIT4
JAVA UNIT4
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.
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.
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.
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:-
Program:
Output:
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
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:
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:
Program
Output:-
Concept:-17 Java util Classes and Interfaces
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:
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?