0% found this document useful (0 votes)
9 views108 pages

Java Packages, Interfaces, and Exception Handling

Unit III of the Advanced Object Oriented Programming course covers Java packages, interfaces, and exception handling. It explains how to define and use packages, the advantages of using them, and the structure of interfaces for achieving abstraction and multiple inheritance. Additionally, it details exception handling mechanisms in Java, including try-catch blocks, checked and unchecked exceptions, and the use of keywords like throw and throws.

Uploaded by

hi2bhavya
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)
9 views108 pages

Java Packages, Interfaces, and Exception Handling

Unit III of the Advanced Object Oriented Programming course covers Java packages, interfaces, and exception handling. It explains how to define and use packages, the advantages of using them, and the structure of interfaces for achieving abstraction and multiple inheritance. Additionally, it details exception handling mechanisms in Java, including try-catch blocks, checked and unchecked exceptions, and the use of keywords like throw and throws.

Uploaded by

hi2bhavya
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

21CSC206P - ADVANCED OBJECT ORIENTED AND

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

• A java package is a group of similar types of classes, interfaces and sub-


packages.

• 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

• The package keyword is used to create a package in java.


//save as [Link]
package mypack;
public class Simple
{
public static void main(String args[])
{
[Link]("Welcome to package");
}
}
How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

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.

To Compile: javac -d . [Link]


To Run: java [Link]

Output:Welcome to package

The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination.

The . represents the current folder.


How to access package from another package?

• 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.

Example of package that import the packagename.*


//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello
2) Using [Link]

If you import [Link] then only declared class of this package will be accessible.

Example of package by import [Link]


//save by [Link]

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.

Example of package by import fully qualified name


//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
Output:Hello
INTERFACE IN JAVA

• An interface in java is a blueprint of a class. It has static constants and


abstract methods.
• The interface in java is a mechanism to achieve abstraction and multiple
inheritance.
• Interface is declared by using interface keyword. It provides total
abstraction; means all the methods in interface are declared with empty
body and are public and all fields are public, static and final by default.
• A class that implement interface must implement all the methods declared
in the interface.
How to declare an interface?

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:

1) We can’t instantiate an interface in java. That means we cannot create the


object of an interface
2) Interface provides full abstraction as none of its methods have body. On
the other hand abstract class provides partial abstraction as it can have
abstract and concrete(methods with body) methods both.
3) “implements” keyword is used by classes to implement an interface.
4) While providing implementation in class of any method of an interface, it
needs to be mentioned as public.
5) Class that implements any interface must implement all the methods of
that interface, else the class should be declared abstract.
6) Interface cannot be declared as private, protected or transient.
7) All the interface methods are by default abstract and public.
8) Variables declared in interface are public, static and final by default.
9) Interface variables must be initialized at the time of declaration otherwise
compiler will throw an error.
interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x is
not initialized at the time of declaration.
10) Inside any implementation class, you cannot change the variables
declared in interface because by default, they are public, static and final
11) An interface can extend any interface but cannot implement it. Class
implements interface and interface extends interface.
12) A class can implement any number of interfaces.
Exceptions

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

• All exception classes are subtypes of the [Link] class. The


exception class is a subclass of the Throwable class.
Key words used in Exception handling

• There are 5 keywords used in java exception handling.

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.

3. finally A finally block of code always executes, irrespective of occurrence of an


Exception.

4. throw It is used to execute important code such as closing connection, stream


etc. throw is used to invoke an exception explicitly.

5. throws throws is used to postpone the handling of a checked exception.


Categories of Exceptions

Checked exceptions −A checked exception is an exception that occurs


at the compile time, these are also called as compile time exceptions.
These exceptions cannot simply be ignored at the time of compilation,
the programmer should take care of (handle) these exceptions.

Unchecked exceptions − An unchecked exception is an exception that


occurs at thetime 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.
Java try block

• 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{

//code that may throw an exception

}catch(Exception_class_Name ref){}
Syntax of try-finally block

try{
//code that may throw an exception
}finally{}

Java catch block

• 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 out exception description.

• Prints the stack trace (Hierarchy of methods where the exception occurred).

• Causes the program to terminate.

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

public class TryCatchExample1


O/P
{
• Exception in thread "main"
public static void main(String[] args) [Link]: / by zero
{
int data=50/0; //may throw exception

[Link]("rest of the code");

}
}
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

public class TryCatchExample2


{
public static void main(String[] args)
{
try OUTPUT:
{
int data=50/0; //may throw exception [Link]: / by zero
} rest of the code
//handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
}
}
The code in a try block that will not throw an exception

public class TryCatchExample3


{
public static void main(String[] args)
{
try
OUTPUT :
{ java. lang. ArithmeticException: / by zero
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute

[Link]("rest of the code");


}
// handling the exception
catch(ArithmeticException e)
{
[Link](e);
}
}
To print a custom message on exception.
public class TryCatchExample5
{
public static void main(String[] args) O/P:
{ Can't divided by zero
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
[Link]("Can't divided by zero");
}
}
}
Enclose exception code in a catch block along with try block

public class TryCatchExample7 {


Output:
public static void main(String[] args) { Exception in thread "main”
[Link]: / by
try zero
{
int data1=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// generating the exception in catch block
int data2=50/0; //may throw exception

}
[Link]("rest of the code");
}
}
Arithmetic Exception with a different type of exception class ArrayIndexOutOfBoundsException

public class TryCatchExample8 {

public static void main(String[] args) { O/P:


try Exception in thread "main"
{ [Link]:
int data=50/0; //may throw exception / by zero
}
// try to handle the ArithmeticException using ArrayI
ndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
}
}
To handle another unchecked exception

public class TryCatchExample9 {


Output:
public static void main(String[] args) { [Link]
try Exception: 10
{ rest of the code
int arr[]= {1,3,5,7};
[Link](arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
}

}
To handle checked exception
import [Link];
import [Link]; Output:
File saved successfully
public class TryCatchExample10 {

public static void main(String[] args) {

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

• A try block can be followed by one or more catch blocks.


• Each catch block must contain a different exception handler.
• So, if you have to perform different tasks at the occurrence of different exceptions, use java
multi-catch block.
• Point to be considered:
• At a time only one exception occurs and at a time only one catch block is executed.
• All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Example of java multi-catch block
public class MultipleCatchBlock1 {

public static void main(String[] args) {

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

In Java, using a try block inside another try block is permitted.


• It is called as nested try block.
• Every statement that we enter a statement in try block, context of that exception is
pushed onto the stack.

For example, the inner try block can be used to


handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).
Syntax
....
//main try block //exception message
try }
{
statement 1; }
statement 2; catch(Exception e1)
// {
try catch block within another try block //exception message
try }
{ }
statement 3; //
statement 4; catch block of parent (outer) try bloc
//try catch block within nested try block k
try catch(Exception e3)
{ {
statement 5; //exception message
statement 6; }
}
catch(Exception e2)
{
Example
//catch block of inner try block 2
public class NestedTryBlock{ catch(ArrayIndexOutOfBoundsException e)
public static void main(String args[]){ {
//outer try block [Link](e);
try{ }
//inner try block 1 [Link]("other statement");
try{ }
[Link]("going to divide by 0"); //catch block of outer try block
int b =39/0; catch(Exception e)
} {
//catch block of inner try block 1 [Link]("handled the exception (outer catch)"
catch(ArithmeticException e) );
{ }
[Link](e); [Link]("normal flow..");
} }
//inner try block 2 }
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
Java finally block
• Java finally block is a block used to execute important code such as closing the
connection, etc.
• Java finally block is always executed whether an exception is handled or not.
Therefore, it contains all the necessary statements that need to be printed regardless of
the exception occurs or not.
• The finally block follows the try-catch block.
Why use Java finally block?
• finally block in Java can be used to put "cleanup" code such as closing a file, closing
connection, etc.
• The important statements to be printed can be placed in the finally block.

Usage of Java finally


Case 1: When an exception does not occur
Case 2: When an exception occurr but not handled by the catch block
Case 3: When an exception occurs and is handled by the catch block
Case 1: When an exception does not occur

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.

Java throw keyword

• The Java throw keyword is used to throw an exception explicitly.


• We specify the exception object which is to be thrown. The Exception has some
message with it that provides the error description. These exceptions may be
related to user inputs, server, etc.
• We can throw either checked or unchecked exceptions in Java by throw keyword.
It is mainly used to throw a custom exception. We will discuss custom exceptions
later in this section.
Example 1: Throwing Unchecked Exception

public class TestThrow1 {


//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");

}
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

S. No. Basis of Differences throw throws


1. Definition Java throw keyword is used throw an Java throws keyword is used in the method
exception explicitly in the code, inside the signature to declare an exception which
function or the block of code. might be thrown by the function while the
execution of the code.
2 Applicable To Type of exception Using throw keyword, Using throws keyword, we can declare both
we can only propagate unchecked checked and unchecked exceptions.
exception i.e., the checked exception However, the throws keyword can be used to
cannot be propagated using throw only. propagate checked exceptions only.
3 Syntax The throw keyword is followed by an The throws keyword is followed by class
instance of Exception to be thrown. names of Exceptions to be thrown.
4 Declaration throw is used within the method. throws is used with the method signature.
5 Internal We are allowed to throw only one We can declare multiple exceptions using
implementation exception at a time i.e. we cannot throw throws keyword that can be thrown by the
multiple exceptions. method. For example, main() throws
IOException, SQLException.
Java throw Example

public class TestThrow {


//defining a method
public static void checkNum(int num) {
if (num < 1) {
throw new ArithmeticException("\
nNumber is negative, cannot calculate square");
}
else {
[Link]("Square of " + num + " is " + (num*num))
;
}
}
//main method
public static void main(String[] args) {
TestThrow obj = new TestThrow();
[Link](-3);
[Link]("Rest of the code..");
}
}
Java throws Example
public class TestThrows {
//defining a method
public static int divideNum(int m, int n) throws ArithmeticException
{
int div = m / n;
return div;
}
//main method
public static void main(String[] args) {
TestThrows obj = new TestThrows();
try {
[Link]([Link](45, 0));
}
catch (ArithmeticException e){
[Link]("\nNumber cannot be divided by 0");
}

[Link]("Rest of the code..");


} }
Difference between final, finally and finalize
• The final, finally, and finalize are keywords in Java that are used in
exception handling.
• Each of these keywords has a different functionality.
• The basic difference between final, finally and finalize is that the final is an
access modifier, finally is the block in Exception Handling and finalize is
the method of object class.
S. No. Key final finally finalize
1. Definition final is the keyword and access finally is the block in Java finalize is the method in Java
modifier which is used to apply Exception Handling to which is used to perform clean
restrictions on a class, method or execute the important code up processing just before object
variable. whether the exception occurs is garbage collected.
or not.
2. Applicable to Final keyword is used with the Finally block is always finalize() method is used with
classes, methods and variables. related to the try and catch the objects.
block in exception handling.
3. Functionality (1) Once declared, final variable (1) finally block runs the finalize method performs the
becomes constant and cannot be important code even if cleaning activities with respect
modified. exception occurs or not. to the object before its
(2) final method cannot be (2) finally block cleans up all destruction.
overridden by sub class. the resources used in try
(3) final class cannot be inherited. block

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

public class FinalExampleTest {


//declaring final variable
final int age = 18;
void display() {
// reassigning value to age variable
// gives compile time error
age = 55;
}
public static void main(String[] args) {

FinalExampleTest obj = new FinalExampleTest


();
// gives compile time error
[Link]();
}}
Java finally Example
public class FinallyExample {
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 occurred or not
finally {
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
} }
Java finalize Example
public class FinalizeExample {
public static void main(String[] args)
{
FinalizeExample obj = new FinalizeExample();
// printing the hashcode
[Link]("Hashcode is: " + [Link]());
obj = null;
// calling the garbage collector using gc()
[Link]();
[Link]("End of the garbage collection");
}
// defining the finalize method
protected void finalize()
{
[Link]("Called the finalize() method");
}}
Input/Output – I/O Basics

• Java I/O (Input and Output) is used to process the input and produce the output.

• Java uses the concept of a stream to make I/O operation fast.

• The [Link] package contains all the classes required for input and output operations.

• We can perform file handling in Java by Java I/O API.


Stream

• A stream is a sequence of data. In Java, a stream is composed of bytes.

• 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

• OutputStream class is an abstract class.


• It is the superclass of all classes representing an output stream of bytes.
• An output stream accepts output bytes and sends them to some sink.
• These streams are used to write data as outputs into an array or file or any output peripheral
device.
Output Stream
Input Stream

• InputStream class is an abstract class.


• It is the superclass of all classes representing an input stream of bytes.
• These streams are used to read data that must be taken as an input from a source array or file
or any peripheral device.
Input Stream
Types of Stream based on types of file

• 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

BufferedInputStream It is used for Buffered Input Stream.

DataInputStream It contains method for reading java standard datatypes.

FileInputStream This is used to reads from a file

InputStream This is an abstract class that describes stream input.

PrintStream This contains the most used print() and println() method

BufferedOutputStream This is used for Buffered Output Stream.

DataOutputStream This contains method for writing java standard data types.

FileOutputStream This is used to write to a file.

OutputStream This is an abstract class that describe stream output.


CharacterStream

• 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

BufferedReader It is used to handle buffered input stream.

FileReader This is an input stream that reads from file.

InputStreamReader This input stream is used to translate byte to character.

OutputStreamReader This output stream is used to translate character to byte.

Reader This is an abstract class that define character stream input.

PrintWriter This contains the most used print() and println() method

Writer This is an abstract class that define character stream output.

BufferedWriter This is used to handle buffered output stream.

FileWriter This is used to output stream that writes to file.


Reading console input

• 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 command-line arguments are stored in the


String format.
• The parseInt method of the Integer class converts
string argument into Integer.
• Similarly, for float and others during execution.
• The usage of args[] comes into existence in this input
form.
• The passing of information takes place during the
Output:
program run. javac [Link]
java Main Hello World
• The command line is given to args[]. These
The command line arguments are:
programs have to be run on cmd. Hello
World
Writing console input

• 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

 Java Print Writer class is the implementation of Writer class.


 “PrintWriter is a class used to write any form of data e.g. int, float, double, String or Object in the form of
text either on the console or in a file in Java.”
 It is used to print the formatted representation of objects to the text-output stream.
 The PrintWriter class of the [Link] package can be used to write output data in a commonly readable form
(text).
 It extends the abstract class Writer.

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

void println(boolean x) It is used to print the boolean value.

void println(char[] x) It is used to print an array of characters.

void println(int x) It is used to print an integer.

PrintWriter append(char c) It is used to append the specified character to the writer.

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.

protected void setError() It is used to indicate that an error occurs.

protected void clearError() It is used to clear the error state of a stream.

PrintWriter format(String format, Object... args) It is used to write a formatted string to the writer using specified arguments and format
string.

void print(Object obj) It is used to print an object.

void flush() It is used to flushes the stream.

void close() It is used to close the stream.


ObjectStreamClass

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

The ObjectInputStream class provides implementations of different methods


present in the InputStream class.

 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);

// Writing to the file using ObjectOutputStream


[Link](data1);
[Link](data2);
Example 1: Java ObjectInputStream(Contd.,)

FileInputStream fileStream = new FileInputStream("[Link]");


// Creating an object input stream
ObjectInputStream objStream = new ObjectInputStream(fileStream);

//Using the readInt() method


[Link]("Integer data :" + [Link]());

// Using the readObject() method


[Link]("String data: " + [Link]());

[Link]();
[Link]();
}
catch (Exception e) { Output
[Link](); Integer data: 5 String data: This is
programiz
}
}
}
Other Methods of ObjectInputStream

Methods Descriptions

returns the available number of bytes in


available()
the input stream

marks the position in input stream up to


mark()
which data has been read

returns the control to the point in the


reset()
input stream where the mark was set

skips and discards the specified bytes


skipBytes()
from the input stream

close() closes the object input stream


ObjectOutputStream Class

The ObjectOutputStream class of the [Link] package can be used to write objects that can
be read by ObjectInputStream.

It extends the OutputStream abstract class.


Working of ObjectOutputStream

 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

The ObjectOutputStream class provides implementations for different methods


present in the OutputStream class.

 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 {

FileOutputStream file = new FileOutputStream("[Link]");

// 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);

[Link]("Integer data :" + [Link]());


[Link]("String data: " + [Link]());
[Link]();
[Link]();
}
catch (Exception e) {
[Link](); Output:
}} Integer data: 5
String data: This is programiz
Serialization and Deserialization in Java
 Serialization in Java is a mechanism of writing the state of an object into a byte-stream.
It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

 The reverse operation of serialization is called deserialization where byte-stream is


converted into an object.

 The serialization and deserialization process is platform-independent, it means you can


serialize an object on one platform and deserialize it on a different platform.

 For serializing the object, we call the writeObject() method of ObjectOutputStream


class, and for deserialization we call the readObject() method of ObjectInputStream
class.
 We must have to implement the Serializable interface for serializing the object.
Advantages of Java Serialization

 It is mainly used to travel object's state on the network (that is known as


marshalling).
[Link] interface
 Serializable is a marker interface (has no data member and method).
 It is used to "mark" Java classes so that the objects of these classes may get
a certain capability.

 The Cloneable and Remote are also marker interfaces.

 The Serializable interface must be implemented by the class whose object


needs to be persisted.

 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:

 import [Link]; // Import the File class

 File myObj = new File("[Link]"); // Specify the filename


Java File Handling

Method Type Description

canRead() Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath() String Returns the absolute pathname of the file

length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory

mkdir() Boolean Creates a directory


Create a File

 To create a file in Java, use the createNewFile() method.

 This method returns a boolean value: true if the file was


successfully created, and false if the file already exists.

 Note:method is enclosed in a try...catch block.

 This is necessary because it throws an IOException if an error


occurs (if the file cannot be created for some reason):
Create a File
import [Link]; // Import the File class
import [Link]; // Import the IOException class to handle errors

public class CreateFile {


public static void main(String[] args) {
try {
File myObj = new File("[Link]");
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
}
} catch (IOException e) {
[Link]("An error occurred."); Output:
[Link]();
} File created: [Link]
}
}
Create a File

 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:

File myObj = new File("C:\\Users\\MyName\\[Link]");


Write To a File
Example:
import [Link]; // Import the FileWriter class
import [Link]; // Import the IOException class to handle errors

public class WriteToFile {


public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("[Link]");
[Link]("Files in Java might be tricky, but it is fun enough!");
[Link]();
[Link]("Successfully wrote to the file.");
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
}
}.
} Output: Successfully wrote to the file
Read a File
Example:
import [Link]; // Import the File class
import [Link]; // Import this class to handle errors
import [Link]; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("[Link]");
Scanner myReader = new Scanner(myObj);
while ([Link]()) {
String data = [Link]();
[Link](data);
}
[Link]();
} catch (FileNotFoundException e) {
[Link]("An error occurred.");
[Link](); } }}
Delete a File

Example:

import [Link]; // Import the File class

public class DeleteFile {


public static void main(String[] args) {
File myObj = new File("[Link]");
if ([Link]()) {
[Link]("Deleted the file: " + [Link]());
} else {
[Link]("Failed to delete the file.");
}
}
}
Delete a Folder

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

You might also like