0% found this document useful (0 votes)
30 views113 pages

OOP JAVA M3 Ktunotes - in

Uploaded by

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

OOP JAVA M3 Ktunotes - in

Uploaded by

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

CST 205 Object Oriented Programming using Java

(As per KTU 2019 Syllabus)

Module 3

Downloaded from Ktunotes.in


Module 3 Lectures

Downloaded from Ktunotes.in


M1 - Packages
● Packages are optional UML constructs that enable you to organize model
elements (such as use cases) into groups.
● Packages are depicted as file folders and can be used on any of the UML
diagrams, including both use case diagrams and class diagrams

Downloaded from Ktunotes.in


Package in Java
● A package in Java is used to group related classes.
● Think of it as a folder in a file directory.
● We use packages to avoid name conflicts, and to
write a better maintainable code.
● Packages are divided into two categories:
● Built-in Packages (packages from the Java API)
● User-defined Packages (create your own packages)

Downloaded from Ktunotes.in


Defining a package
• To create a package, simply include a package command as the first
statement in a Java source file.
– All classes declared in that file will belong to the specified package.
• The package statement defines a name space in which classes are stored.
• If we are not writing package statement, the class names are put into the
default package, which has no name.
General form for creating a package : package packagename;
Example: If we write the following statement at the beginning beginning of our
java program program then it will create a package named Oop.
package Oop;

Downloaded from Ktunotes.in


Defining a package
Java uses file system directories to store packages.

Example: Any classes that we declare to be part of the package GECI must
store their .class files in a directory called GECI.

• Any file can include the same package statement.


• The package statement simply specifies to which package the classes
defined in a file belongs to.

Downloaded from Ktunotes.in


Defining a package
We can create a hierarchy of packages.
– Separate each package name from other using period(dot) symbol.
• General form of a multileveled package statement is :
package pkg1.pkg2.pkg3;
This specifies specifies that package package pkg3 is inside package
package pkg2 and pkg2 package is inside pkg1.
• E.g The package declared as
package java.awt.image;
– needs to be stored in the path java\awt\image in a Windows environment

• We cannot rename a package without renaming the directory


in which the classes are stored.
Downloaded from Ktunotes.in
Importing Packages
• All of the standard classes are stored in some named package.
• If we want to use classes in some other packages, they must be fully
qualified with their package name or names, It is difficult to type in the long
dot-separated package path name for every class we want to use.

– TO SOLVE THIS PROBLEM, we can use import


statement. The import statement helps to bring certain
classes, or entire packages, into visibility.
• To use a class or a package from the library, we need to use the
import keyword
• import statements is written after the package statement(if
exists) and before all class definitions.
Downloaded from Ktunotes.in
Importing Packages
• General form of the import statement:
import pkg1[.pkg2].(classname|*);
Eg : java.lang.* ;

– Here, pkg1 is the name of a top-level package, and pkg2 is the name
of a subordinate package inside the package pkg1 separated by a dot
(.). Here square bracket denotes that it is optional.
• E.g.
import pack1; // import the package pack1
import java.io.*; // import all the classes from the package java.io
import java.util.Date; //import the Date class from the package java.util

Downloaded from Ktunotes.in


Importing Packages
• All of the standard Java classes included with Java
are stored in a package called java

• The basic language functions are stored in a package


inside of the java package called java.lang

– it is implicitly imported by the compiler for all


programs

Downloaded from Ktunotes.in


Importing Packages
• Using an import statement:
import java.util.*;
class MyDate extends Date {
//statements , methods,variables
}
• Without the import statement looks like this:
class MyDate extends java.util.Date
{
}

Downloaded from Ktunotes.in


Importing Packages
Without Using import statement- we have to use class from other package as
packagename.classname (fully quantified)

Using import package.classname statement to import a class in package to


program file in another package.

Using import package.* statement to import all classes in pack1 to program


file in pack2

Downloaded from Ktunotes.in


Example
• Create a folder pack1 inside D drive
• Create a file A.java
package pack1;
public class A
{
public static void main(String args[] ) {
System.out.println("Hello");
}
public void show() {
System.out.println(“show in A");
}
}
Downloaded from Ktunotes.in
Example
Method 1
• Take path before pack1 folder in command prompt here
it s D drive.
• Compile using
D:\>javac pack1/A.java
• To run
D:\>java pack1/A
Or
D:\>java pack1.A

Downloaded from Ktunotes.in


Example
Method 2
• Set classpath in command prompt to path to folder before
the package pack1
C:\Users\USER>set CLASSPATH=;D:\
To compile
C:\Users\USER>javac -cp . D:\pack1\A.java
To run
C:\Users\USER>java pack1.A
Hello

Downloaded from Ktunotes.in


Example
Method 3:
• Using –classpath option
• Compile using
C:\Users\USER>javac D:\pack1\A.java
Or
C:\Users\USER>javac -classpath . D:\pack1\A.java
• Run using
C:\Users\USER>java -classpath D:\ pack1.A

Downloaded from Ktunotes.in


Using import statement
• Create a folder pack2 inside D drive
• Create a file B.java in it
package pack2;
import pack1.*;
class B{
public static void main(String args[])
{
A obj = new A();
obj.show();
System.out.println(“main in class B");
}
}
Downloaded from Ktunotes.in
Java Foundation Packages
• Java provides a large number of classes grouped into different packages
based on their functionality.
• The six foundation Java packages are:
– java.lang : Contains classes for primitive types, strings, math functions,
threads, and exception
– java.util : Contains classes such as vectors, hash tables, date etc.
– java.io : Stream classes for I/O
– java.awt : Classes for implementing GUI – windows, buttons, menus etc.
– java.net : Classes for networking
– java.applet : Classes for creating and implementing applets

Downloaded from Ktunotes.in


Finding Packages and CLASSPATH
How does the Java run-time system know where to look for
packages that we create?
1. By default, the Java run-time system uses the current
working directory as its starting point.
if our package is in a subdirectory of the current
directory, it will be found.
2. We can specify a directory path or set paths by setting the
CLASSPATH environment variable.
3. We can use the -classpath option with java and javac to
specify the path to your classes.

Downloaded from Ktunotes.in


CLASSPATH
• Example
package MyPack;
• For a program to find MyPack, one of three things must be true.
– Either the program can be executed from a directory immediately above
MyPack or
– the CLASSPATH must be set to include the path to MyPack, or
– the -classpath option must specify the path to MyPack when the program is
run via java
• To execute the program
– java MyPack.programname

Downloaded from Ktunotes.in


CLASSPATH
In the case of CLASSPATH and –classpath option , the class
path must not include MyPack, itself. It must simply specify
the path to MyPack.
• Suppose the path of MyPack directory is
C:\MyPrograms\Java\MyPack
– Then the class path to MyPack is C:\MyPrograms\Java

java -classpath C:\MyPrograms\Java MyPack.programname

Downloaded from Ktunotes.in


package mypack; class packagetest
{
class balance public static void main(String args[])
{ {
String name; balance b[]=new balance[3];
int bal; b[0]=new balance("ABC",123);
balance(String n, int b) b[1]=new balance("EFG",157);
{ b[2]=new balance("IJK",10);
name=n; for(int i=0;i<3;i++)
bal=b; b[i].show();
} }
void show() }
{

System.out.println("-->");
System.out.println(name+": $"+bal);

}
}

Downloaded from Ktunotes.in


Access Modifiers in Java
● private - Visible to the class only. [Class level]
● default - Visible to the package. No modifiers are needed. [Package level]
● protected - Visible to the package and all subclasses. [Package + Subclass]
● public - Visible to the world. [All]

Downloaded from Ktunotes.in


M1 - Member visibility
PRIVATE
PROTECTED DEFAULT /
PACKAGE

PUBLIC

Downloaded from Ktunotes.in


M1 - Relationships between classes
6. Generalization (Inheritance)
● A generalization helps to connect a subclass to its superclass.
● A sub-class is inherited from its superclass.
● A solid line with a hollow arrowhead that point from the child to the parent class
7. Realization (Implements)
● Realization relationship is a relationship between two model elements, in which
one model element (the client) realizes (implements or executes) the behavior
that the other model element (the supplier) specifies.

Downloaded from Ktunotes.in


Interface
Like a class, an interface can have methods and variables, but the methods
declared in an interface are by default abstract (only method signature, no
body).

Interfaces specify what a class must do and not how. It is the blueprint of the
class.

An Interface is about capabilities like a Car may be an interface and any class
implementing Car must be able to (or must implement) start(). So it specifies a
set of methods that the class has to implement.

If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.

Downloaded from Ktunotes.in


Interfaces
● An interface in the Java programming language is an abstract type that is
used to specify a behavior that classes must implement.
● They are similar to protocols - programming by contract
● Interfaces are declared using the interface keyword, and may only contain
method signature and constant declarations
● Syntactically similar to classes but they lack instance variables and their
methods are declared without any body
● You can specify what a class must do not how to do
● A class can implement any number of interfaces
● An interface extends other interfaces

Downloaded from Ktunotes.in


Interfaces

● Remember - Java does not multiple inheritance

Downloaded from Ktunotes.in


Need for Interface
It is used to achieve total abstraction.

Since java does not support multiple inheritance in case of


class, but by using interface it can achieve multiple inheritance
.

Interfaces are used to implement abstraction. So the question


arises why use interfaces when we have abstract classes?

The reason is, abstract classes may contain non-final


variables, whereas variables in interface are final, public and
static

Downloaded from Ktunotes.in


Interface syntax
Interface can be created using the keyword interface.

• Interfaces are syntactically similar to classes.

• Interface does not have instance variables.

• The methods in interface are declared without any body.

• Any number of classes can implement an interface.

• One class can implement any number of interfaces.

Downloaded from Ktunotes.in


Interface syntax
• When no access specifier is included, then it has
default access.
– the interface is only available to other members of
the package in which it is declared.
• The methods are declared have no bodies. They
end with a semicolon after the parameter list.
• They are abstract methods.
• Each class that includes an interface must
implement all of the methods. (else ?)
• Variables are implicitly final and static, meaning
they cannot be changed by the implementing class.
– They must also be initialized.
• All variables and methods are implicitly public

Downloaded from Ktunotes.in


Implementing an Interface
General form of a class that includes the implements clause
class classname [extends superclass] [implements
interface [,interface...]]
{
// class-body
}
//square bracket denotes optional
• Each class can have its own implementation of the
methods.

• By providing the interface keyword, Java allows you to fully


utilize the “one interface, multiple methods” aspect of
polymorphism.

• Interfaces support dynamic method resolution at run time.

Downloaded from Ktunotes.in


Extending Interface
● Class implements
interface

● Class can extend with


one parent class

● Interface can extend


any number of
interfaces

Downloaded from Ktunotes.in


Accessing Implementations Through Interface References
• We can declare variables as
object references that use an
interface rather than a class
type.

• Any instance of any class that


implements the declared
interface can be referred to by
such a variable

interfacename obj=object of
implementing class;

Downloaded from Ktunotes.in


Nested Interfaces

An interface can be declared a member of a class or another interface. Such an


interface is called a member interface or a nested interface.

A nested interface can be declared as public, private, or protected if it is declared


inside a class.

The top level interface must either be declared as public or use the default access
level.
Downloaded from Ktunotes.in
New features added in interfaces in JDK 8
● Prior to JDK 8, interface could not define
implementation. We can now add default
implementation for interface methods.
● This default implementation has special use
and does not affect the intention behind
interfaces.
● Suppose we need to add a new function in an
existing interface.
● Obviously the old code will not work as the
classes have not implemented those new
functions. So with the help of default
implementation, we will give a default body for
the newly added functions. Then the old codes
will still work
Downloaded from Ktunotes.in
New features added in interfaces in JDK 8
● Another feature that was added in
JDK 8 is that we can now define
static methods in interfaces which
can be called independently without
an object. Note: these methods are
not inherited.

Downloaded from Ktunotes.in


Lecture 3 - Input / Output

Downloaded from Ktunotes.in


Input/Output basics
● Only print( ) and println( ) are used
frequently.
System.out.print()
System.out.println()

● All other I/O methods are not used


significantly.– Because most real
applications of Java are not text-based,
console programs.

● Java’s support for console I/O is


limited.

Downloaded from Ktunotes.in


I/O Stream
Stream is a sequence of bytes
Java programs perform I/O through streams.
A stream is an abstraction that either produces or consumes information(bytes).
A stream is a sequence of objects that supports various methods.
A stream is linked to a physical device by the Java I/O system.
– Input stream may refer to different kinds of input: from a disk file, a keyboard, or a
network socket
– Output stream may refer to the console, a disk file, or a network connection.

Downloaded from Ktunotes.in


Byte and Character stream
• The java.io package contains all the classes required for input and output
operations.
• Java defines two types of streams: byte and character.
• Byte streams provides a means for handling input and output of bytes.
– Byte streams are used when reading or writing binary data.
• Character streams provide a means for handling input and output of characters.
– they use Unicode.

– in some cases,
character streams are more efficient
than byte stream

Downloaded from Ktunotes.in


Java I/O class hierarchy

Downloaded from Ktunotes.in


Byte stream classes

Downloaded from Ktunotes.in


Byte stream
classes

Downloaded from Ktunotes.in


Character Streams
• Character streams are defined by using two class hierarchies.
At the top are two abstract classes,
– Reader and Writer.
• Java has several concrete subclasses of each of these.
• Two of the most important methods are read( ) and write( ).
– These methods are overridden by derived stream classes.

Note:
Usually character stream class names will end with
er [Reader , Writer]

Downloaded from Ktunotes.in


Character Stream Classes

Downloaded from Ktunotes.in


Character Stream Classes

Downloaded from Ktunotes.in


The Predefined Streams
• All Java programs automatically import the java.lang package.
This package defines a class called System.
• System contains three predefined stream variables:
– in, out, and err.
– These fields are declared as public, static, and final within System.
• System.out refers to the standard output stream.
• System.in refers to standard input, which is the keyboard by default.
• System.err refers to the standard error stream, which is the console by default.

System.in is an object of type InputStream;

System.out and System.err are objects of type PrintStream.

Downloaded from Ktunotes.in


Reading Console input
• The preferred method of reading console input is to use a character-oriented
stream.
• In Java, console input is accomplished by reading from System.in [ InputStream ]
– To obtain a character based stream that is attached to the console, wrap System.in
in a BufferedReader object.

• BufferedReader supports a buffered input stream.


– Its most commonly used constructor is:
BufferedReader(Reader inputReader)
• Here, inputReader is the stream that is linked to the instance of BufferedReader that
is being created.
Reader is an abstract class.

Downloaded from Ktunotes.in


Reading Console input
• One of the concrete subclasses of Reader is InputStreamReader.
• InputStreamReader converts bytes to characters.
– It reads bytes and decodes them into characters using a specified charset.
• To obtain an InputStreamReader object that is linked to System.in, the constructor
that can be used is :
InputStreamReader(InputStream inputStream)
• Following line of code creates a BufferedReader that is connected to the
keyboard:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
• By wrapping the System.in (standard input stream) in an InputStreamReader
which is wrapped in a BufferedReader, we can read input from the user in the
command line.
• After this statement executes, br is a character-based stream that is linked to the
console through System.in
Downloaded from Ktunotes.in
Downloaded from Ktunotes.in
Reading Console summary

Downloaded from Ktunotes.in


Reading characters

• To read a character from a BufferedReader, use read( ).

The version of read( ) is int read( ) throws IOException

• Each time that read( ) is called, it reads a character from the input stream and
returns it as an integer value.

It returns –1 when the end of the stream is encountered

Downloaded from Ktunotes.in


Reading characters

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Reading Strings

• To read a string from the keyboard, use the version of readLine( ) that is a
member of the BufferedReader class.

Its general form is String readLine( ) throws IOException

This returns a String object.

Downloaded from Ktunotes.in


Reading Strings

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Reading Console Input

Downloaded from Ktunotes.in


Scanner class

Downloaded from Ktunotes.in


Writing Console Output
• Console output is usually done through print( ) and println().
• These methods are defined by the class PrintStream.

– It is the type of object referenced by System.out.

– System.out is a byte stream,


• PrintStream is an output stream derived from OutputStream,

– PrintStream also implements the low-level method write( ).


– write( ) can be used to write to the console.

Downloaded from Ktunotes.in


Writing Console Output
The simplest form of write( ) defined by PrintStream is void write(int byteval)
– This method writes the byte specified by byteval to the stream
– byteval is declared as an integer, only the low-order eight bits are written.
// Demonstrate System.out.write().Write letter ‘A’ to console.
classWriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}

Downloaded from Ktunotes.in


PrintWriter class
• For real-world programs, the recommended method of writing to the console using
Java is through a PrintWriter stream.

• PrintWriter is one of the character-based classes.


• PrintWriter defines several constructors.
PrintWriter(OutputStream outputStream, boolean flushOnNewline)

• Here, outputStream is an object of type OutputStream, and flushOnNewline


controls whether Java flushes the output stream every time a println( ) method is
called.

– If flushOnNewline is true, flushing automatically takes place. If false, flushing is


not automatic.
Downloaded from Ktunotes.in
PrintWriter class
• PrintWriter supports the print() and println( ) methods

• If an argument is not a simple type, the PrintWriter methods


call the object’s toString( ) method and then print the result.

• To write to the console by using a PrintWriter, specify

System.out for the output stream and flush the stream after
each new line.
PrintWriter pw = new PrintWriter(System.out, true);

Downloaded from Ktunotes.in


PrintWriter class

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Exception handling

Downloaded from Ktunotes.in


Errors and Exceptions in Java
● An exception is an event, which occurs during the execution of a program, that
disrupts the normal flow of the program's instructions.
● Errors represent serious and usually irrecoverable conditions like a library
incompatibility, infinite recursion, or memory leaks.
● If these exceptions are not prevented or at least handled properly, either the
program will be aborted abnormally, or the incorrect result will be carried on.
● In traditional programming languages like C, Pascal etc. this exception handling is
an overhead of the programmer to make the program robust.
● Java programmer are released from this overhead by the exception handling
mechanism in Java.
● When an error/exception occurs, Java will normally stop and generate an error
message. The technical term for this is: Java will throw an exception (throw an
error) Downloaded from Ktunotes.in
Categories of Exceptions
● Checked exceptions − A checked exception is an exception that is checked
(notified) by the compiler at compilation-time, these are also called as
compile time exceptions. These exceptions cannot simply be ignored, the
programmer should take care of (handle) these exceptions
● Unchecked exceptions − An unchecked exception is an exception that
occurs at the time of execution. These are also called as Runtime Exceptions.
These include programming bugs, such as logic errors or improper use of an
API. Runtime exceptions are ignored at the time of compilation
● Errors − These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer. Errors are typically ignored in your
code because you can rarely do anything about an error. For example, if a
stack overflow occurs, an error will arise. They are also ignored at the time of
compilation

Downloaded from Ktunotes.in


Exception hierarchy

Checked - Exception handling code


is needed to complete the
compilation successfully

Unchecked - Exception handling


code is not mandatory

Downloaded from Ktunotes.in


Exception handling
● Exception is an object that describes exceptional condition that has occurred
in a piece of code
● Exception object is created and thrown from the method that generate error
● It is caught and handled automatically or manually

Five key words

1. try - The block of code which can produce exception is kept under try block
2. throw - To throw an exception from a method to its calling method
3. throws - To declare a method which can throw exception
4. catch - This block catches the exception from try block (at least one catch)
5. finally - This block is after the catch block, executes always
Downloaded from Ktunotes.in
Exception handling
try { // block of code
}
catch ( ExceptionType1 e) {
// Exception handling routine for ExceptionType1 (optional)

}
catch (ExceptionType2 e ) {
// Exception handling routine for ExceptionType2 (optional)

}
. .
.
catch (ExceptionType_n e) {
// Exception handling routine for ExceptionType_n }
finally {
Downloaded from Ktunotes.in
No exception Exception

Downloaded from Ktunotes.in


Multiple catch block
● When more than one exception could be raised from a single piece of code
● Specify more than one catch block
● Each will be inspected in order
● The first matching catch is selected and rest is bypassed
● So catch specific exception classes in the initial catch blocks
● Last catch block shall catch "Exception" object to catch all

Downloaded from Ktunotes.in


Order of catch blocks
class try1
{
public static void main(String args[])
{
try
{
int a=args.length;
System.out.println("a=" +a);
}
catch(Exception e)
{
System.out.println(e);
}
catch(ArithmeticException ae )
{
System.out.println(ae);
}

System.out.println("This is after try catch");


}
}
Downloaded from Ktunotes.in
The throws/throw Keywords
● If a method does not handle a checked exception, the method must declare it
using the throws keyword. The throws keyword appears at the end of a
method's signature.
● You can throw an exception, either a newly instantiated one or an exception
that you just caught, by using the throw keyword.
● throws is used to postpone the handling of a checked exception and throw is
used to invoke an exception explicitly.

Downloaded from Ktunotes.in


The throw keyword
● The throw statement allows you to create a custom exception.
● The throw statement is used together with an exception type.
○ There are many exception types available in Java: ArithmeticException, FileNotFoundException,
ArrayIndexOutOfBoundsException, SecurityException
○ User defined exception type cna ve created by inheriting Exception class

Downloaded from Ktunotes.in


User defined Exception type

Downloaded from Ktunotes.in


Working with Files in Java
In Java, all files are byte-oriented.
• Java provides methods to
– read bytes from a file and
– write bytes to a file.

– byte stream and character stream classes


Byte stream classes for File operations
Two of the most often-used file stream classes are
FileInputStream - FileInputStream is an input stream to read data
from a file in the form of sequence of bytes
FileOutputStream - FileOutputStream class is an output stream for
writing data to a file
It is recommended not to use the FileInputStream and FileOutputStream classes if
you have to read and write any textual information as these are Byte stream
classes. In such case use character stream classes
Downloaded from Ktunotes.in
Exceptions during file operations
• Exceptions(run time error) like FileNtotFoundException (if the given filename is
not in the system path) may occur during file operations.
– So it is better to enclose file operation statements within try block for handling
exceptions.
• If the file we try to read a file that does not exist, then that exception is caught by
the following catch block and the corresponding action in it is done.

try{
//File Operation statements
}
catch(FileNotFoundException e)
{
System.out.println("File not found"); //print this message if file is not found
}

Downloaded from Ktunotes.in


Open a file for read/write
• To open a file, create an object of one of classes, specify the name of the file as
an argument to the constructor.
• If we want to open a file for reading – Create object of FileInputStream class
• If we want to open a file for writing - – Create object of FileOutputStream class
• Main constructors are
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName, boolean append) throws FileNotFoundException
– Here, fileName specifies the name of the file (as String i.e. enclose in
double quotes) that we want to open.
– When we create an input stream, if the file does not exist, then
FileNotFoundException is thrown.
– For output streams, if the file cannot be created, then FileNotFoundException is
thrown.
– When an output file is opened, any file that is already existing with the same
name as output file is destroyed.
Downloaded from Ktunotes.in
Open a file for read/write
• To open a file, create an object of one of classes, specify the name of the file as
an argument to the constructor.
• If we want to open a file for reading – Create object of FileInputStream class
• If we want to open a file for writing - – Create object of FileOutputStream class
• Main constructors are
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
– Here, fileName specifies the name of the file (as String i.e. enclose in
double quotes) that we want to open.
– When we create an input stream, if the file does not exist, then
FileNotFoundException is thrown.
– For output streams, if the file cannot be created, then FileNotFoundException
is thrown.
– When an output file is opened, any file that is already existing with the same
name as output file is destroyed. To append use constructor with append flag.
Downloaded from Ktunotes.in
Close a file after read/write
• After completing file read or write operations, we should close the file by calling
close( ) method on stream object.

• It is defined by both FileInputStream and FileOutputStream :

void close( ) throws IOException

E.g. to close file Sample.txt opened for reading

FileInputStream fileobject;
fileobject = new FileInputStream(“Sample.txt");
//statements for reading the file
fileobject.close();

Downloaded from Ktunotes.in


Reading from a file
• To read data from a file,
1. First, we have to create FileInputStream class object and pass filename as the
parameter to the constructor.

FileInputStream fileobject;
fileobject = new FileInputStream(“Sample.txt");
2. Next,we can use a version of read( ) that is defined within FileInputStream. int
read( ) throws IOException

int c=fileobj.read();

• Each time read() called, it reads a single byte from the file and returns the byte as
an integer value.
– read( ) returns –1 when the end of the file is encountered.
– read() can throw an IOException.
Downloaded from Ktunotes.in
Reading from a file

Downloaded from Ktunotes.in


Writing to a file
• To write to a file, we can use the write( ) method defined by FileOutputStream.
void write(int byteval) throws IOException
– This method writes the byte specified by byteval to the file.
– Although byteval is declared as an integer, only the loworder eight bits are written
to the file.
– If an error occurs during writing, an IOException is thrown

1. First, we have to create FileOutputStream class object and pass filename as the
parameter to the constructor.
2. Using write function store the byte value in file
int c=65;
FileOutputStream fileobject;
fileobject = new FileOutputStream(“Sample.txt");
fileobject.write(c);
• Here lower order will be stored.So this will store ASCII value of 65 that is letterA in
file Sample.txt Downloaded from Ktunotes.in
Writing to a file

Downloaded from Ktunotes.in


Working with Files in Java
In Java, all files are byte-oriented.
• Java provides methods to
– read bytes from a file and
– write bytes to a file.
– byte stream and character stream classes

Character stream classes for File operations


Two of the most often-used file stream classes are
FileReader- is an input stream to read data from a file in the form of sequence of
characters
FileWriter - is an output stream for writing characters to a file

It is recommended not to use the FileInputStream and FileOutputStream classes if


you have to read and write any textual information as these are Byte stream
classes. In such case use character stream classes
Downloaded from Ktunotes.in
FileReader
• The FileReader class creates a Reader that we can use to read the contents of a
file.
• Its two most commonly used constructors are shown here:

FileReader(String filePath)
FileReader(File fileObj)

– They can throw a FileNotFoundException. Here, filePath is the full path name of
a file, and fileObj is a File object that describes the file

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
FileWriter
• FileWriter creates a Writer that you can use to write to a file.
• Its most commonly used constructors are:
FileWriter(String filePath)
FileWriter(String filePath, boolean append)
FileWriter(File fileObj)
FileWriter(File fileObj, boolean append)
– They can throw an IOException. Here, filePath is the full path name of a file, and fileObj
is a File object that describes the file.
If append is true, then output is appended to the end of the file.
• FileWriter will create the file before opening it for output when you create the object.
– In the case where we attempt to open a read-only file, an IOException will be thrown.
• getChars( ) method is used to extract the character array equivalent.
public void getChars(int srhStartIndex, int srhEndIndex,char[] destArray, int destStartIndex)
Parameters:
srhStartIndex : Index of the first character in the string to copy.
srhEndIndex : Index after the last character in the string to copy.
destArray : Destination array where chars wil get copied.
destStartIndex : Index in the array starting from where the chars will be
pushed into the array. Return: It does not return any value.

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
Object Streams and Serialization
● Java provides a mechanism, called object serialization where an object can
be represented as a sequence of bytes that includes the object's data as well
as information about the object's type and the types of data stored in the
object.
● Object streams support I/O(input-output) of objects
● The object stream classes are
● – ObjectInputStream
● – ObjectOutputStream

Downloaded from Ktunotes.in


Serialization & Deserialization
● Serialization is the process of writing(converting) the state of an object to a
byte stream.
● – This is useful when we want to save(store) the state of the program to a
persistent(permanent) storage area, such as a file or
● when we want to send it over network.
● Later we can restore these objects by using the process of deserialization.
● – Deserialization converts byte streams into object.
Applications: Storage of objects on files, Passing objects over network (Java
Remote Method invocation etc.)

Downloaded from Ktunotes.in


Serialization & Deserialization
• If we attempt to serialize an object at the top of an object graph,
– all of the other referenced objects are recursively located and serialized.

• Similarly, during the process of deserialization, all of these objects and their
references are correctly restored when deserialization is done at the top.

Downloaded from Ktunotes.in


Interfaces for Serialization
Interfaces that support serialization are:
– Serializable
– Externalizable

Serializable is a marker interface i.e. does not contain any method.

Externalizable interface contains two methods writeExternal() and readExternal()


which implementing classes MUST override.

Externalizable provides control of serialization logic to programmer – to write


custom logic.

Downloaded from Ktunotes.in


Serializable Interface
– Only an object that implements the Serializable interface can be saved and
restored by the serialization facilities.
– The Serializable interface defines no members.
– It is simply used to indicate that a class may be serialized.
– If a class is serializable, all of its subclasses are also serializable.
– Variables that are declared as transient and static variables are not saved by the
serialization facilities.

Downloaded from Ktunotes.in


transient keyword
The transient keyword in Java is used to avoid serialization.

If any object of a data structure is defined as a transient , then it will not be


serialized.

In below example SSN will not be serialized

Downloaded from Ktunotes.in


Serialization

Downloaded from Ktunotes.in


Deserialization

Downloaded from Ktunotes.in


Externalizable Interface
Externalization serves the purpose of custom Serialization, where we can decide
what to store in stream.
Externalizable interface present in java.io, is used for Externalization which
extends Serializable interface.
It consist of two methods which we have to override to write/read object into/from
stream which are.
– The programmer may need to have control over these processes.
– it may be desirable to use compression or encryption techniques.
• The Externalizable interface is designed for these situations.
• The Externalizable interface defines two methods:
void readExternal(ObjectInput inStream) throws IOException,
ClassNotFoundException
void writeExternal(ObjectOutput outStream) throws IOException

• inStream is the byte stream from which the object is to be read


• outStream is the byte Downloaded
stream to which the object is to be written
from Ktunotes.in
Downloaded from Ktunotes.in
Deserialization

Downloaded from Ktunotes.in


Downloaded from Ktunotes.in
ObjectOutput methods

Downloaded from Ktunotes.in


ObjectOutputStream methods

Downloaded from Ktunotes.in


ObjectOutput & ObjectOutputStream
• The ObjectOutput interface extends the DataOutput interface and supports
object serialization.
• It defines the methods such as writeObject( )
• writeObject( ) method is called to serialize an object.
• All of these methods will throw an IOException on error conditions
ObjectOutputStream
• The ObjectOutputStream class extends the OutputStream class and implements
the ObjectOutput interface.
• It is responsible for writing objects to a stream.
• A constructor of this class is ObjectOutputStream(OutputStream outStream)
throws IOException
– The argument outStream is the output stream to which serialized objects will be
written.
• Methods in this class will throw an IOException on error conditions.
• There is also an inner class to ObjectOuputStream called PutField.
– It facilitates the writingDownloaded
of persistent fields.
from Ktunotes.in
ObjectInput methods

Downloaded from Ktunotes.in


ObjectInputStream methods

Downloaded from Ktunotes.in


ObjectInput & ObjectInputStream
• The ObjectInput interface extends the DataInput interface and defines the method
such as readObject( ) method.
• This is called to deserialize an object.
• All of these methods will throw an IOException on error conditions.
• The readObject( ) method can also throw ClassNotFoundException
ObjectInputStream
• The ObjectInputStream class extends the InputStream class and implements the
ObjectInput interface.
• ObjectInputStream is responsible for reading objects from a stream.
• A constructor of this class is ObjectInputStream(InputStream inStream) throws
IOException
– The argument inStream is the input stream from which serialized objects should be read.
• The meThods will throw an IOException on error conditions.
• The readObject() method can also throw ClassNotFoundException.
• There is also an inner class to ObjectInputStream called GetField. It facilitates the
reading of persistent fieldsDownloaded from Ktunotes.in
Serialization and inheritance
Case 1: If superclass is serializable then subclass is automatically serializable : If
superclass is Serializable, then by default every subclass is serializable. Hence, even
though subclass doesn’t implement Serializable interface( and if it’s superclass
implements Serializable), then we can serialize subclass object.

Case 2: If a superclass is not serializable then subclass can still be serialized : Even
though superclass doesn’t implements Serializable interface, we can serialize subclass
object if subclass itself implements Serializable interface. So we can say that to
serialize subclass object, superclass need not to be serializable.

Downloaded from Ktunotes.in


References
● Herbert Schildt, Java: The Complete Reference, 8/e, Tata McGraw Hill, 2011.

● Visual Paradigm - www.visual-paradigm.com

● GeeksforGeeks - www.geeksforgeeks.org

● Wikipedia - www.wikipedia.org

● Tutorialspoint - www.tutorialspoint.com

● Java Zone - https://dzone.com


Disclaimer - This document contains images/texts from various internet sources. Copyright belongs to the
respective content creators. Document is compiled exclusively for study purpose and shall not be used for
commercial purpose.

Downloaded from Ktunotes.in

You might also like