0% found this document useful (0 votes)
10 views57 pages

Unit 4

Uploaded by

hasinikkvl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views57 pages

Unit 4

Uploaded by

hasinikkvl
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

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, class Math, Wrapper Classes,
Auto-boxing and Auto-unboxing.

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, custom exceptions.

Java I/O and File: Java I/O API, standard I/O streams, types, Byte streams,
Character streams, Scanner class, Files in Java: File, FileInputStream and
FileOutputStream Classes
Packages and JAVA Library
• JAVA follows OOP
• Number of built in classes and interfaces are there – JAVA 8 - 217 Packages and
4240 Classes.
• For proper management of classes and interfaces, the related classes and
interfaces are grouped into packages and sub-packages.
• The default package is java.
• A large number of the packages and sub-packages are contained in the package
java.
Packages as Name Space
• A package provides a name space in which the classes and
interfaces have unique names.
• Same names may be used in different packages without
ambiguity.
• Similarly, the class name and interface also provide name spaces
in which the names of variables and methods are unique.
Built-in Packages
Package Name Description

java.lang Contains language support classes ( for e.g classes which defines primitive data types,
math operations, etc.) . This package is automatically imported.
java.io Contains classes for supporting input / output operations.
Contains utility classes which implement data structures like List, Hash Table,
java.util Dictionary, etc and support for Date / Time operations. This package is also called as
Collections.

java.applet Contains classes for creating Applets.

java.awt Contains classes for implementing the components of graphical user interface ( like
buttons, menus, etc. ).
java.net Contains classes for supporting networking operations.

This package helps to develop GUI like java.awt. The ‘x’ in javax represents that it is
javax.swing an extended package which means it is a package developed from another package
by adding new features to it. In fact, javax.swing is an extended package of java.awt.

java.sql This package helps to connect to databases like Oracle/Sybase/Microsoft Access to


perform different operations.
User defined packages
• One of the important features of the Java is that it allows a
programmer to build his/her own packages and classes.
• A programmer can save his/her own packages and classes in a
directory, and from there, it can be imported to the application
program by using import keyword.

• To create a user defined package, in program the first


instruction must be
package packagename;
Defining a Package
• A package comprises a group of similar type of classes, interfaces,
and sub-packages.
• It is defined with the keyword package followed by the name of the
package and a semicolon

• Package statement is the first statement in a program, No other


code line can be placed above it expect the comments.
Defining a Package
• Rules:
• All the members of a package must have unique names, otherwise
compile-type error will occur.
• Packages also provide an access control mechanism.
• A class which is not public is accessible to other classes in the
same package.
• A package that is not a sub-package of another package can have
a simple name. Examples are java, javax, and javafx
• Qualified name:
• If a package contained another sub-packages we use qualified
name.
• Qualified name consists of names of pakages/sub-package
separated by .(dot)
Defining a Package
package java.mypackage.xpack.ypack;// qualifi ed name for ypack

package java.mypackage;// qualified name for mypackage

package java.mypackage.xpack; // qualified name for xpack

package java.mypackage.xpack.ypack;// qualified name for ypack


Importing Packages and Classes into
Programs
• Most of the Java programs need to refer to one or more packages and classes in
the source code.
• If a program needs several classes of a package, it is better to import the whole
package

• For a particular class may be included in a program by importing it through its


fully qualified name
How to access package from another
package?
There are three ways to access the package
• import package.*;
• import package.classname;
• fully qualified name.
PATH and CLASSPATH
• PATH - is an environment variable is
used to tell the location of built-in
directories such as javac and java,
jar, javadoc, appletviewer ...
• Path tells the system where to locate
the JDK files that contain these
commands.
• CLASSPATH –
• The class path environment
variable is used to specify the
location of the classes and
packages.
• is an environment variable is
used to specify the location of
user Class files.
CLASSPATH
• First, by default, the Java run-time system uses the current
working directory as its starting point.
• If your package is in a subdirectory of the current directory, it
will be found.
• Second, you can specify a directory path or paths by setting
the CLASSPATH environmental variable.
– Ex: Pack_Example.java is in G Drive and Package is in D drive
G:\>set CLASSPATH=D:\Materials\JAVA Material\Unit
2\23.12.19;.;
• Third, you can use the –cp(classpath) option with java and javac to specify
the path to your classes.

• If it is not working use ;.; after path

“D:\Materials\JAVA Material\Unit 2\23.12.19 Pack”;.;


jar file(Java Archive)
• JAR (JAVA Archive) file is a file that contains compressed
venison of class files, audio files, image files and directories.
• To create JAR file use jar command
– jar cf outputfile_name.jar input_files
• jar cf file_name
• jar cvf file_name – create verbose
• jar tf file_name - table view of file contents
• jar xf file_name - extract file
How to use JAR files
• Goto the environment variables.
• Goto user variables and click on new button
• Set the classpath
– Variable name CLASSPATH
– Variable value
D:\Materials\JAVA Material\Unit 2\23.12.19\PVPSIT.jar;.;

• Click OK and Close


Access Control
• The packages are containers of sub-packages, classes, and
interfaces.
• The encapsulation of related classes in packages provides two
benefits:
(i) Name space
(ii) Access protection
• A class may be declared with access specifiers such as public,
private, protected and without any access specifier.
• Generally, protected and private are used only in nested classes.
Access specifiers for classes
Control of access to class members
java.lang Package and its classes
• java.lang package is imported into every Java program by default.
• This package contains classes and interfaces that are essential for
the design of Java programming language and are as follows:
• Object class is the root of all classes
• Primitive data types
• Classes access system resources and other low level entities
• Math class – for mathematical operations
• Class Throwable – for errors and exceptions
• Thread class – to implement threads
• To work with strings such as String, StringBuffer
• Boolean − The Boolean class wraps a value of the primitive type boolean in an object.
• Byte − The Byte class class wraps a value of primitive type byte in an object.
• Character − The Character class offers a number of useful class (i.e., static) methods
for manipulating characters.
• Class − The Class class instance represent classes and interfaces in a running Java
application. It has no public constructor.
• String − Strings, which are widely used in Java programming, are a sequence of
characters. In Java programming language, strings are treated as objects. The Java
platform provides the String class to create and manipulate strings.
• StringBuffer − The StringBuffer class is mutable sequence of characters. StringBuffer
can be used to modify the content of a String with ease. It provides many utility
functions to manipulate a string.
• StringBuilder − The StringBuilder class is mutable sequence of characters. This
provides an API compatible with StringBuffer, but with no guarantee of
synchronization.
• System − The System class contains several useful class fields and methods. It cannot
be instantiated.
Interfaces defined in java.lang package
1. Appendable
This interface is designed for objects that can have characters or sequences of characters
appended to them.
Classes that implement this interface include StringBuilder and BufferedWriter.
2. AutoCloseable
This interface provides a mechanism for objects that need to release resources when they are
no longer in use. It has a single method: close().
Commonly used with the try-with-resources statement. Many classes like FileInputStream and
Scanner implement this interface.
3. CharSequence
Represents a readable sequence of characters. It is a base interface for several classes like
String, StringBuilder, and StringBuffer.
4. Cloneable
This interface indicates that a class can be cloned, meaning it supports the creation of an exact
copy of its instances using the clone() method.
Classes implementing this interface can override the clone() method from Object to allow for
object duplication.
5. Comparable<T>
This interface is used to impose a natural ordering on objects of each class that
implements it. It contains the method compareTo(T o). .
6. Iterable<T>
This interface represents a collection of objects that can be iterated over, typically
using a for-each loop.
It defines the method iterator(). Collections like List and Set implement this interface.
7. Readable
This interface represents a source of characters that can be read into a CharBuffer. It
has a single method: read(CharBuffer cb).
8. Runnable
This interface is used for classes whose instances are intended to be executed by a
thread. It has a single method: run().
It is commonly implemented when creating threads in Java, either directly or
indirectly via the Thread class.
Class Object
• It is the super class for all classes in Java. This class has one
constructor and 11 methods.
Class Math
• The Math class is an important class of java.lang package.
• It defines methods for evaluating several mathematical functions
such as trigonometry functions (sine, cosines, etc.), exponential
functions, rounding off functions, and other miscellaneous
mathematical functions.
• The class is defined as a final class.
public final class Math extends Object
All the methods defined in Math class are static, and thus they
may be called without ‘object’. However class name is required.
Method Description Return Type

abs(x) Returns the absolute value of x double|float|int|long

acos(x) Returns the arccosine of x, in radians double

addExact(x, y) Returns the sum of x and y int|long

asin(x) Returns the arcsine of x, in radians double

atan(x) Returns the arctangent of x as a numeric value double


between -PI/2 and PI/2 radians

cbrt(x) Returns the cube root of x double

ceil(x) Returns the value of x rounded up to its nearest Double


integer
cos(x) Returns the cosine of x (x is in radians) double
cosh(x) Returns the hyperbolic cosine of a double double
value

decrementExact(x) Returns x-1 int|long


floor(x) Returns the value of x rounded down to its double
nearest integer
Wrapper Classes
• In Java, everything can be viewed as an object.
• A simple data type can also be converted into an object using
Wrapper classes.
• As the name suggests, a Wrapper class wraps (i.e., encloses) a
primitive data type and provides its object representation .
• Need of Wrapper Classes:
• Objects are needed if we wish to modify the arguments passed into a
method (because primitive types are passed by value).
• The classes in java.util package handles only objects and hence wrapper
classes help in this case also.
• Data structures in the Collection framework, such as ArrayList and
Vector, store only objects (reference types) and not primitive types.
• An object is needed to support synchronization in multithreading.
Wrapper Classes
• The eight primitive data types, namely boolean, byte, short, int, long, float,
double, and char, are not objects of classes;
• They cannot be passed on by references and they are passed on by value
only.
• In order to provide object representation, eight Wrapper classes are defined
in java.lang package.
Pimitive Data Type Wrapper Class

char Character

byte Byte

short Short

int Integer

long Long

float Float

double Double

boolean Boolean
Constructors of Wrapper Classes
class Byte
Byte (byte Numb) The
Byte (String Strnumb) throws NumberFormatException NumberFormatE
xception occurs
class Short when the string
Short (short numb) is not in
appropriate
Short (String Strnumb) throws NumberFormatException
format.

class Integer
Integer (int numb)
Integer (String Strnumb) throws NumberFormatException.
class Float
Float (float numb or double number)
Float (String Strnumb) throws NumberFormatException
Constructors of Wrapper Classes
class Double
Double(double d)
Double (String Strnumb) throws NumberFormatException

class Character
Character (char ch)

class Boolean
Boolean (boolean value)
Boolean (String boolstring)

Java has deprecated these constructors in favor of using valueOf() or autoboxing.


First see Ex1.java , then see UseofValueOf.java example program
Methods of Wrapper Classes

• The valueOf() method in Java is a static method available in various wrapper


classes like Integer, Double, Boolean, etc.

• It is used to convert a string or a primitive value into an object of the


corresponding wrapper class. This method is frequently used when you
need to convert a primitive type or a string into an object

• static T valueOf(type number) - Returns the type of object containing value


passed as part of number

• static T valueOf(String number) - Returns the type of object containing


value passed as part of number

UseofValueOf.java
Methods of Wrapper Classes

•Integer Class
• public static Integer valueOf(int i)
• public static Integer valueOf(String s)
•Double Class
• public static Double valueOf(double d)
• public static Double valueOf(String s)
Boolean Class
public static Boolean valueOf(boolean b)
public static Boolean valueOf(String s)
Methods of Wrapper Classes

Method Description
byte byteValue() is used to convert an object of a wrapper class (such as
Integer, Float, Double, etc.) to a byte primitive type.
int intValue() Returns the value as an int primitive type.
long longValue() Returns the value as a long primitive type.
short shortValue() Returns the value as a short primitive type.
double doubleValue() Returns the value as a double primitive type.
float floatValue() Returns the value as a float primitive type.

These methods are defined in the Number class (which is the superclass of
classes like Integer, Long, Float, etc.), so they are available in various wrapper
classes.

String toString() Returns the string equivalent of invoking object

Ex2.java
Methods for Conversion of Digital Strings
into numbers
• In Java, the parse methods are used to convert strings to their respective
primitive numeric types.
• They are commonly used to parse numeric values from user input, text files, or
other sources where numbers are stored as strings.
• These methods are part of the wrapper classes like Integer, Double, Float, Byte,
Short, and Long.

Ex3.java
Auto-boxing and Un-boxing
• Auto-boxing involves automatic conversion of the primitive
data types into its corresponding wrapper types.
• This includes the conversion of int to Integer, double to
Double, float to Float, boolean to Boolean, etc.,
• Unboxing is the reverse process in which the wrapping class
objects are converted into the corresponding primitive data
types
• This includes conversion of Integer to int, Long to long,
Double to double, etc
• Java 5 introduced the feature of auto-conversion of primitive
data types to the corresponding Wrapper class objects and
vice versa.

Autoboxing_UnBoxing.java
Methods isInfinite() and isNaN()
• The methods isInfinite() and isNaN() are used in Java to check
if a floating-point value is either infinite or "Not-a-Number"
(NaN).
• These methods are available in the Double and Float wrapper
classes.
• isInfinite() is occurer due to large number/small number
• Ex: 2522256897771/2, number/0
• isNaN() checks whether the invoking object is number or not
As per textbook
Exception Handling
Exception Handling
• types of errors
– Compile, run-time, logical errors(incorrect o/p)
• Logical Errors
• Multiplying when you should be dividing
• Adding when you should be subtracting
• Opening and using data from the wrong file
• Displaying the wrong output

• Exceptions – occurred during running and classified into checked or unchecked.


• An exception is undesirable that may occur during the execution of the program
and may lead to termination of the program if it is not handled properly.
• try
• catch
• throw - explicitly raise
• throws – not in a position to handle
• finally – always execute irrespective of exception occurred or not

39
try { General form-of exception handling block
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
• Here, ExceptionType is the type of exception that has occurred.
Exception heirarchy

Error - Out of memory error or a System crash error

42
FAQs
• What is Throwable?
– Throwable is a super class that represents all errors and exceptions
• Which is the super class for all exceptions?
• What is the difference between exception & error?
– An exception is an error which can be handled. It means when an exception
happens, the programmer can do something to avoid harm.
– But an error is an error which can not be handled (Programmer can not do
anything –catastrophically errors)
• What are checked exceptions?
– That are checked at compilation time by the Java compiler
• What are unchecked exceptions?
– That are checked by JVM
try bocks
• The program code that is most likely to create
exceptions is kept in the try block, which is followed by
the catch block to handle the exception.
• In normal execution, the statements are executed and
if there are no exceptions, the program flow goes to
the code line after the catch blocks.
• However, if there is an exception, an exception object
is thrown from the try block.
• Its data members keep the information about the type
of exception thrown.
• The program flow comes out of the try block and
searches for an appropriate catch block with the same
type as its argument.
catch block
• A catch block is meant to catch the exception if the
type of its argument matches with the type of
exception thrown.
• If the type of exception does not match the type of
the first catch block, the program flow checks the
other catch blocks one by one.
• If the type of a catch block matches, its statements
are executed.
• If none matches, the program flow records the
type of exception, executes the finally block, and
terminates the program.
Multiple catch clauses
• In some cases, 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.
• If one catch statement is executed, the others are
bypassed, and execution continues after the try / catch
block.
• When you use multiple catch statements, it is
important to remember that exception subclasses must
come before any of their super classes.
• This is because a catch statement that uses a super
class will catch exceptions of that type plus any of its
subclasses. Subclass would never be reached if it
came after its super class.
• Since Java 7, a modification has been done in the
language so that one catch block can catch more than
one type of exception.
• The exception classes are connected by Boolean
operator |.
Java finally block
• Java finally block is a block that is used to
execute important code such as closing
connections (databases, network, disks,
commit in databases) etc.
• Java finally block is always executed whether
exception is handled or not.
Use of throw – to generate and for
rethrowing exceptions
• So far, you have only been catching exceptions that are
thrown by the Java run-time system. However, it is possible
for your program to throw an exception explicitly, using
throw statement.
• The general form of throw is shown here:
throw ThrowableInstance;
• Here, ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
• There are two ways to obtain a Throwable instance:
- creating one with the new operator
throw new exception_class("error message");
- using the parameter of catch clause -
throw exception_type_variable; (For rethrowing)

• The flow of execution stops immediately after the throw


statement; any subsequent statements are not executed.
• The nearest enclosing try block is inspected to see if it has a
catch statement that matches the type of exception.
• If it does find a match, control is transferred to that statement.
• If no matching catch is found, then the default exception handler
halts the program and prints the stack trace.
Use of throws clause
• throws is a keyword in Java that is used in the signature
of a method to indicate that this method might throw one
of the listed type exceptions(Checked or un-checked).
• The caller to these methods has to handle the exception
using a try-catch block.

type method-name(parameter-list) throws exception-list


{
// body of method
}
Custom Exceptions
• We can also create our own exception by creating a sub class
simply by extending java Exception class.
class UserException extends Exception
• Define a constructor in UserException (optional)
– UserException();
– UserException (parameter);
The first form creates an exception that has no description.
The second form lets you specify a description of the
exception.
• To print custom messages:
– Override toString() method
– toString() method to display customized message in catch clause.

You might also like