Java Packages, Interfaces, and Exception Handling
Java Packages, Interfaces, and Exception Handling
PROGRAMMING
UNIT - III
UNIT - III
• Defining Package
• CLASSPATH, Access Protection
• Importing Packages, Interfaces.
• Exception Handling
• Checked Exceptions, Unchecked Exceptions
• try Block and catch Clause
• Multiple catch clauses
• Nested try Statements
• throw, throws and finally
• Input/Output - I/O Basics
• Reading Console Input
• Writing Console Output
• Print Writer Class
• Object Streams and Serialization
• Working with Files.
Java Package
• Package in java can be categorized in two form, built-in package and user-
defined package.
• There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
• Here, we will have the detailed learning of creating and using user-defined
packages.
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.
3) Java package removes naming collision.
Simple example of java package
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . [Link]
The -d switch specifies the destination where to put the generated class file.
You can use any directory name like /home (in case of Linux), d:/abc (in case
of windows) etc. If you want to keep the package within the same directory,
you can use . (dot).
How to run java package program
You need to use fully qualified name e.g. [Link] etc to run the class.
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination.
• There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.
The import keyword is used to make the classes and interface of another package accessible to the current package.
If you import [Link] then only declared class of this package will be accessible.
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
3) Using 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. [Link] and [Link] packages contain Date
class.
interface <interface_name>{
// declare constant fields
// declare methods that abstract
// by default.
}
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends another interface, but a class
implements an interface.
Example of Interface
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
[Link]("ROI: "+[Link]());
}} Output: ROI:9.15
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as multiple
inheritance.
Example of Multiple Inheritance
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable{
public void print(){[Link]("Hello");}
public void show(){[Link]("Welcome");}
public static void main(String args[]){
A7 obj = new A7();
[Link]();
[Link]();
}
}
Key points to remember about interfaces:
Exceptions are conditions within the code. A developer can handle such
conditionsand take necessary corrective actions. Few examples
DivideByZero exception
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
• An exception (or exceptional event) is a problem that arises during the
execution of a program.
• When an Exception occurs the normal flow of the program is disrupted
and the program/Application terminates abnormally, which is not
recommended, therefore, these exceptions are to be handled.
Exception Hierarchy
1. try A try/catch block is placed around the code that might generate an exception.
Code within a try/catch block is referred to as protected code.
2. catch A catch statement involves declaring the type of exception we are trying to catch.
• Java try block is used to enclose the code that might throw an exception.
• It must be used within the method.
• If an exception occurs at the particular statement in the try block, the rest of the block
code will not execute.
• So, it is recommended not to keep the code in try block that will not throw an exception.
• Java try block must be followed by either catch or finally block.
Syntax of Java try-catch
try{
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw an exception
}finally{}
• 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 good approach is to declare the generated type of exception.
•The catch block must be used after the try block only. You can use multiple catch block with a single
try block.
Internal Working of Java try-catch block
The JVM firstly checks whether the exception is handled or not. If exception is not
handled, JVM provides a default exception handler that performs the following tasks:
• Prints the stack trace (Hierarchy of methods where the exception occurred).
But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
Problem without exception handling
}
}
As displayed in the above example, the rest of the code is not executed (in such case,
the rest of the code statement is not printed).
There might be 100 lines of code after the exception.
If the exception is not handled, all the code below the exception won't be executed.
Solution by exception handling
}
[Link]("rest of the code");
}
}
Arithmetic Exception with a different type of exception class ArrayIndexOutOfBoundsException
}
To handle checked exception
import [Link];
import [Link]; Output:
File saved successfully
public class TryCatchExample10 {
PrintWriter pw;
try {
pw = new PrintWriter("[Link]"); //may throw exception
[Link]("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {
[Link](e);
}
[Link]("File saved successfully");
}
}
Java Catch Multiple Exceptions
try{ Output
int a[]=new int[5]; Arithmetic Exception occurs
a[5]=30/0; rest of the code
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Java Nested try block
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
[Link](data);
}
//catch won't be executed
catch(NullPointerException e){
[Link](e);
}
//executed regardless of exception occurred or not
finally {
[Link]("finally block is always executed")
;
}
[Link]("rest of the code...");
}}
Case 2: When an exception occur but not handled by the catch
block
public class TestFinallyBlock1{
public static void main(String args[]){
try {
[Link]("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
[Link](data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
[Link](e);
}
//executes regardless of exception occured or not
finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
Case 3: When an exception occurs and is handled by the catch block
public class TestFinallyBlock2{
public static void main(String args[]){
try {
[Link]("Inside try block");
//below code throws divide by zero exception
int data=25/0;
[Link](data);
}
//handles the Arithmetic Exception / Divide by zero exception
catch(ArithmeticException e){
[Link]("Exception handled");
[Link](e);
}
//executes regardless of exception occured or not
finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
Java throw Exception
• In Java, exceptions allows us to write good quality codes where the errors are
checked at the compile time instead of runtime and we can create custom
exceptions making the code recovery and debugging easier.
}
else {
[Link]("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
[Link]("rest of the code...");
}
}
Example 2: Throwing Checked Exception
import [Link].*;
public class TestThrow2 {
//function to check if person is eligible to vote or not
public static void method() throws FileNotFoundException {
FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\
[Link]");
BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException();
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
[Link]();
}
[Link]("rest of the code...");
}}
Example 3: Throwing User-defined Exception
// class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
} }
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
[Link]("Caught the exception");
// Print the message from MyException object
[Link]([Link]());
}
}
}
Difference between throw and throws in Java
4. Execution Final method is executed only Finally block is executed as finalize method is executed just
when we call it. soon as the try-catch block is before the object is destroyed.
[Link]'s execution is not
dependant on the exception.
Java final Example
• Java I/O (Input and Output) is used to process the input and produce the output.
• The [Link] package contains all the classes required for input and output operations.
• It's called a stream because it is like a stream of water that continues to flow.
1) [Link]: standard input stream
2) [Link]: standard output stream
3) [Link]: standard error stream
Types of Stream based on types of operation
OutputStream
• Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.
InputStream
• Java application uses an input stream to read data from a source; it may be a file, an array,
peripheral device or socket.
Output Stream
• Streams can be divided into two primary classes which can be further divided into other classes
as can be seen through the diagram below followed by the explanations.
ByteStream
• This is used to process data byte by byte (8 bits). Though it has many classes, the
FileInputStream and the FileOutputStream are the most popular ones.
• The FileInputStream is used to read from the source and FileOutputStream is used to write to the
destination.
Stream class Description
PrintStream This contains the most used print() and println() method
DataOutputStream This contains method for writing java standard data types.
• In Java, characters are stored using Unicode conventions. Character stream automatically allows
us to read/write data character by character. Though it has many classes, the FileReader and the
FileWriter are the most popular ones. FileReader and FileWriter are character streams used to
read from the source and write to the destination respectively.
Stream class Description
PrintWriter This contains the most used print() and println() method
• In Java, there are four different ways for reading input from the user in the command line
environment(console).
1. Using Buffered Reader Class
2. Using Scanner Class
3. Using Console Class
4. Using Command line argument
1. Using Buffered Reader Class
• This method is used by wrapping the [Link] (standard input stream) in an InputStreamReader
which is wrapped in a BufferedReader, we can read input from the user in the command line.
2. Using Scanner Class
• The main purpose of the Scanner class is to parse primitive types and strings using regular
expressions, however, it is also can be used to read input from the user in the command line.
3. Using Console Class
• It has been becoming a preferred way for reading user’s input from the command line.
• In addition, it can be used for reading password-like input without echoing the characters entered
by the user; the format string syntax can also be used (like [Link]()).
4. Using Command Line Argument
• The methods used for streaming output are defined in the PrintStream class.
• The methods used for writing console output are print(), println() and write().
The basic differences between print() and println() methods are as follows:
• print() method displays the string in the same line whereas println() method outputs a newline
character after its execution.
• print() method is used for directing output to console only whereas println() method is used for
directing output to not only console but other sources also.
print()
println()
write()
Java PrintWriter class
Class declaration:
public class PrintWriter extends Writer
Java PrintWriter class
import [Link];
import [Link];
public class PrintWriterExample {
public static void main(String[] args) throws Exception {
//Data to write on Console using PrintWriter
PrintWriter writer = new PrintWriter([Link]);
[Link]("Javatpoint provides tutorials of all technology.");
[Link]();
[Link]();
//Data to write in File using PrintWriter
PrintWriter writer1 =null;
writer1 = new PrintWriter(new File("D:\\[Link]"));
[Link]("Like Java, Spring, Hibernate, Android, PHP etc.");
[Link]();
[Link](); } }
Methods of PrintWriter class
Method Description
PrintWriter append(CharSequence ch) It is used to append the specified character sequence to the writer.
PrintWriter append(CharSequence ch, int start, int end) It is used to append a subsequence of specified character to the writer.
boolean checkError() It is used to flushes the stream and check its error state.
PrintWriter format(String format, Object... args) It is used to write a formatted string to the writer using specified arguments and format
string.
ObjectStreamClass act as a Serialization descriptor for class. This class contains the name
and serialVersionUID of the class.
ObjectInputStream Class
The ObjectInputStream class of the [Link] package can be used to read objects
that were previously written by ObjectOutputStream.
It extends the InputStream abstract class.
Working of ObjectInputStream
The ObjectInputStream is mainly used to read data written by the ObjectOutputStream.
Basically, the ObjectOutputStream converts Java objects into corresponding streams. This is known as
serialization. Those converted streams can be stored in files or transferred through networks.
Now, if we need to read those objects, we will use the ObjectInputStream that will convert the streams
back to corresponding objects. This is known as deserialization.
Create an ObjectInputStream
In order to create an object input stream, we must import the [Link] package first. Once
we import the package, here is how we can create an input stream.
// Creates a file input stream linked with the specified file
FileInputStream fileStream = new FileInputStream(String file);
// Creates an object input stream using the file input stream
ObjectInputStream objStream = new ObjectInputStream(fileStream);
Now, the objStream can be used to read objects from the file.
Methods of ObjectInputStream
read() Method
read() - reads a byte of data from the input stream
readBoolean() - reads data in boolean form
readChar() - reads data in character form
readInt() - reads data in integer form
readObject() - reads the object from the input stream
Example 1: Java ObjectInputStream
import [Link];
import [Link];
import [Link];
import [Link];
class Main {
public static void main(String[] args) {
int data1 = 5;
String data2 = "This is programiz";
try {
FileOutputStream file = new FileOutputStream("[Link]");
ObjectOutputStream output = new ObjectOutputStream(file);
[Link]();
[Link]();
}
catch (Exception e) { Output
[Link](); Integer data: 5 String data: This is
programiz
}
}
}
Other Methods of ObjectInputStream
Methods Descriptions
The ObjectOutputStream class of the [Link] package can be used to write objects that can
be read by ObjectInputStream.
Basically, the ObjectOutputStream encodes Java objects using the class name and object values. And, hence
generates corresponding streams. This process is known as serialization.
Those converted streams can be stored in files and can be transferred among networks.
Note: The ObjectOutputStream class only writes those objects that implement the Serializable interface. This is
because objects need to be serialized while writing to the stream
Create an ObjectOutputStream
In order to create an object output stream - import the [Link] package first.
// Creates a FileOutputStream where objects from ObjectOutputStream are written
FileOutputStream fileStream = new FileOutputStream(String file);
// Creates the ObjectOutputStream
ObjectOutputStream objStream = new ObjectOutputStream(fileStream);
In the above example, we have created an object output stream named objStream that is linked with the file
output stream named fileStream.
Methods of ObjectOutputStream
write() Method
write() - writes a byte of data to the output stream
writeBoolean() - writes data in boolean form
writeChar() - writes data in character form
writeInt() - writes data in integer form
writeObject() - writes object to the output stream
Java ObjectOutputStream
import [Link];
import [Link];
import [Link];
import [Link];
class Main {
public static void main(String[] args) {
int data1 = 5;
String data2 = "This is programiz";
try {
// Creates an ObjectOutputStream
ObjectOutputStream output = new ObjectOutputStream(file);
Java ObjectOutputStream
// writes objects to output stream
[Link](data1);
[Link](data2);
// Reads data using the ObjectInputStream
FileInputStream fileStream = new FileInputStream("[Link]");
ObjectInputStream objStream = new ObjectInputStream(fileStream);
The String class and all the wrapper classes implement the
[Link] interface by default.
Example - Serialization
import [Link].*;
class Persist{
public static void main(String args[]){
try{
//Creating the object
Student s1 =new Student(211,"ravi");
//Creating stream and writing the object
FileOutputStream fout=new FileOutputStream("[Link]");
ObjectOutputStream out=new ObjectOutputStream(fout);
[Link](s1);
[Link]();
//closing the stream
[Link]();
[Link]("success");
}catch(Exception e){[Link](e);}
}
}
Java File Handling
The File class from the [Link] package, allows us to work with
files.
To use the File class, create an object of the class, and specify the
filename or directory name:
To create a file in a specific directory (requires permission), specify the path of the file and
use double backslashes to escape the "\" character (for Windows).
On Mac and Linux you can just write the path, like: /Users/name/[Link]
Example:
Example:
Example:
import [Link];
public class DeleteFolder {
public static void main(String[] args) {
File myObj = new File("C:\\Users\\MyName\\Test");
if ([Link]()) {
[Link]("Deleted the folder: " + [Link]());
} else {
[Link]("Failed to delete the folder.");
}
}
} Output:
Deleted the folder: Test
THANK YOU
109