UNIT-II 5
► Inheritanceis the process by which one object acquires the properties of
another object.
Definition:
► The class that is inherited is called a superclass or baseclass.
► The class that does the inheriting is called a subclass or derivedclass.
► Subclass is a specialized version of a superclass.
UNIT-II 7
The generalform of a class definition that inherits a superclass uses the
keyword extends and is shown as:
class subclass-name extends superclass-
name
{
//body of class
}
Syntax:
8.
UNIT-II 8
Sample program:Single Inheritance
class A
{
int i,j;
void show( )
{
System.out.println(“i=”+i+” j=“+j);
}
}
class B extends A
{
int p,q;
void display( )
{
System.out.println(“p=“+p+” q=“+q);
}
void all( )
{
System.out.println(“i=”+i+” j=“+j+
“ p=“+p+” q=“+q);
}
}
class InheritanceDemo1
{
public static void main(String args[ ])
{
A obj1=new A( );
B obj2=new B( );
obj1.i=10;
obj1.j=20;
obj2.i=30;
obj2.j=40;
obj2.p=50;
obj2.q=60;
obj1.show( );
obj2.display( );
obj2.all( );
obj2.show( );
}
} O/P:
i=10 j=20
p=50 q=60
i=30 j=40 p=50 q=60
i=30 j=40
9.
UNIT-II 9
Java supportsthe following access specifiers(Modifiers)
public
private
protected
No modifier(default)
Although a subclass includes all of the members of its superclass,
it cannot access those members of the superclass that have been
declared as private.
Member Access:
10.
UNIT-II 10
Sample program:Use of private keyword
class A
{
private int i,j;
void show( )
{
System.out.println(“i=”+i+” j=“+j);
}
}
class B extends A
{
int p,q;
void display( )
{
System.out.println(“p=“+p+” q=“+q);
}
void all( )
{
System.out.println(“i=”+i+” j=“+j+
“ p=“+p+” q=“+q);
}
}
class InheritanceDemo2
{
public static void main(String args[ ])
{
A obj1=new A( );
B obj2=new B( );
obj1.i=10;
obj1.j=20;
obj2.i=30;
obj2.j=40;
obj2.p=50;
obj2.q=60;
obj1.show( );
obj2.display( );
obj2.all( );
obj2.show( );
}
}
Compile time ERROR
11.
UNIT-II 11
Superclass variablereferencing a subclass object:
► A reference variable of a superclass can be assigned a reference to
any subclass derived from that superclass.
12.
UNIT-II 12
Sample program:Superclass variable referencing a subclass object
class A
{
int i,j;
void show( )
{
System.out.println(“i=”+i+” j=“+j);
}
}
class B extends A
{
int p,q;
void display( )
{
System.out.println(“p=“+p+” q=“+q);
}
void all( )
{
System.out.println(“i=”+i+” j=“+j+
“ p=“+p+” q=“+q);
}
}
class InheritanceDemo3
{
public static void main(String args[ ])
{
A obj1=new A( );
B obj2=new B( );
obj1.i=10;
obj1.j=20;
obj2.i=30;
obj2.j=40;
obj2.p=50;
obj2.q=60;
obj1.show( );
obj1=obj2;
obj1.show( );
}
}
O/P:
i=10 j=20
i=30 j=40
13.
UNIT-II 13
super keyword:
superhas two general forms:
1) To call the superclass constructor.
2) To access a member of the superclass.
Whenever a subclass needs to refer to its immediate superclass,
it can do so by use of the keyword super.
14.
UNIT-II 14
super tocall the superclass constructor:
► A subclass can call a constructor defined by its superclass by use of
the following form of super:
super(parameter-list)
Note: super( ) must always be the first statement inside a subclass constructor.
15.
UNIT-II 15
class A{
inti, j;
A( ){
System.out.println(“A default”);
}
A(int a, int b){
i=a;
j=b;
System.out.println(“A with 2 args”);
}
void show( ){
System.out.println(“i=”+i+” j=“+j);
}}
class B extends A{
int p,q;
B( ){
System.out.println(“B default”);
}
B(int a, int b, int c, int d){
super(a,b);
p=c;
q=d;
Sample program: super(parameter-list)
System.out.println(“B with 4 args”);
}
void all( ){
System.out.println(“i=”+i+” j=“+j+“ p=“+p+”
q=“+q);
}}
class SuperConstructor{
public static void main(String args[ ]){
A obj1=new A( );
B obj2=new B(30,40,50,60);
obj1.show( );
obj2.all( );
obj2.show( );
}}
O/P:
A default
A with 2 args
B with 4 args
i=0 j=0
i=30 j=40 p=50 q=60
i=30 j=40
16.
UNIT-II 16
► Thissecond form of super is most applicable to situations in which
member names of a subclass hide members by the same name in the
superclass.
Second use of super keyword;
The general form is:
super.member
► The super always refers to the superclass of the subclass in which it is used.
17.
UNIT-II 17
class A{
inti, j;
A( ){
System.out.println(“A default”);
}
A(int a, int b){
i=a;
j=b;
System.out.println(“A with 2 args”);
}
void show( ){
System.out.println(“i=”+i+” j=“+j);
}}
class B extends A{
int i, j, p, q;
B( ){
System.out.println(“B default”);
}
B(int a, int b, int c, int d){
super(a,b);
i=c;
j=d;
Sample program: super.member
System.out.println(“B with 4 args”);
}
void all( ){
System.out.println(“Ai=”+super.i+”Aj=“+
super.j+“ i=“+i+” j=“+j);
}}
class SuperMember{
public static void main(String args[ ]){
A obj1=new A( );
B obj2=new B(30,40,50,60);
obj1.show( );
obj2.all( );
obj2.show( );
}}
O/P:
A default
A with 2 args
B with 4 args
i=0 j=0
Ai=30 Aj=40 i=50 j=60
i=30 j=40
UNIT-II 19
class A
{
inti,j;
A( )
{
System.out.println("A default");
}
}
class B extends A
{
int p,q;
B( )
{
System.out.println("B default");
}
}
Sample Program: Multilevel Inheritance
O/P: ?
class C extends B
{
int x,y;
C( )
{
System.out.println("C default");
}
}
class ConstructorOrder1
{
public static void main(String args[ ])
{
C c1=new C();
}
}
20.
UNIT-II 20
► Ifsuper( ) is not used, then the default or parameter less constructor of each
superclass will be executed.
In what order Constructors are called:
► In a class hierarchy, constructors are called in the order of derivation,
from superclass to subclass.
► Since super( ) must be the first statement executed in a subclass constructor,
this order is the same whether or not super( ) is used.
21.
UNIT-II 21
class Cextends B {
int x,y;
C( ) {
System.out.println("C default");
}
C(int a,int b,int c,int d,int e,int f) {
super(a,b,c,d);
x=e;
y=f;
System.out.println("C 6 args");
}
void display( )
{ System.out.println("i="+i+"j="+j+"p="+p+"q="
+ q+"x="+x+"y="+y);
}}
class ConstructorOrder2 {
public static void main(String args[]) {
C c1=new C(10,20,30,40,50,60);
c1.display();
}}
class A{
int i,j;
A( ) {
System.out.println("A default");
}
A(int a, int b) {
i=a;
j=b;
System.out.println("A 2 args");
}}
class B extends A {
int p,q;
B( ) {
System.out.println("B default");
}
B(int a,int b,int c,int d) {
super(a,b);
p=c;
q=d;
System.out.println("B 4 args");
}}
Sample Program: Multilevel Inheritance
22.
UNIT-II 22
Method Overriding:
►Whena method in a subclass has the same name and type signature as
a method in its superclass, then the method in the subclass is said to
override the method in the superclass.
► When an overriden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass.
► The version of the method defined by the superclass will be hidden.
► The superclass version of an overridden method can be accessed
using super.
23.
UNIT-II 23
class A{
inti, j;
void show( ){
System.out.println(“This is in A’s show “);
}}
class B extends A{
int p, q;
void show( ){
super.show( );
System.out.println(“This is in B’s show “);
}}
class Override{
public static void main(String args[ ]){
A obj1=new A( );
B obj2=new B( );
obj1.show( );
obj2.show( );
}}
Sample program: Method Overriding
O/P:
This is in A’s show
This is in A’s show
This is in B’s show
24.
UNIT-II 24
Dynamic MethodDispatch:
Dynamic method dispatch is the mechanism by which a call to an overridden
function is resolved at run time, rather than compile time.
Java implements run-time polymorphism using dynamic method dispatch.
25.
UNIT-II 25
class A{
void callme( ) {
System.out.println("A's method");
}
}
class B extends A {
void callme( ) {
System.out.println("B's method");
}
}
class C extends A {
void callme( ) {
System.out.println("C's method");
}
}
class DynamicMethodDispatch {
public static void main(String args[]) {
A a1=new A( );
B b1=new B( );
C c1=new C( );
A p1;
p1=a1;
p1.callme( );
p1=b1;
p1.callme( );
p1=c1;
p1.callme();
}
}
Sample program: Dynamic Method Dispatch
O/P:-
A’s method
B’s method
C’s method
26.
UNIT-II 26
Abstract classes:
Anabstract method is a method without implementation.
The general form is:
abstract type name(parameter-list);
Abstract methods must be overridden(implemented) in the subclasses.
Any class that contains one or more abstract methods must be declared
abstract.
An abstract class cannot be directly instantiated with the new keyword.
We cannot declare abstract constructors or abstract static methods.
Any subclass of an abstract class must either implement all of the abstract
methods in the superclass or be itself declared abstract.
An abstract class reference can point to a subclass object.
27.
UNIT-II 27
abstract classA
{
void show( )
{
System.out.println("A's show method");
}
abstract void display(int x,int y);
}
class B extends A
{
void m1( )
{
System.out.println("Method m1");
}
void display(int x, int y)
{
System.out.println("Param1="+x+
" Param2="+y);
}
}
Sample program1: Abstract classes
O/P:-
Param1=10 Param2=20
class AbstractClass
{
public static void main(String args[ ])
{
B b1=new B();
b1.display(10,20);
}
}
28.
UNIT-II 28
Sample program2:Abstract classes
class AbstractClass2
{
public static void main(String args[ ])
{
B b1=new B( );
b1.display(10,20);
A a1;
a1=b1;
a1.display(30,40);
}
}
O/P:-
Param1=10 Param2=20
Param1=30 Param2=40
abstract class A
{
void show( )
{
System.out.println("A's show method");
}
abstract void display(int x,int y);
}
class B extends A
{
void m1( )
{
System.out.println("Method m1");
}
void display(int x, int y)
{
System.out.println("Param1="+x+
" Param2="+y);
}
}
29.
UNIT-II 29
final keyword:
finalcan be applied for variables, methods and classes.
A final variable is a constant.
Methods declared as final cannot be overridden.
Classes declared as final cannot be inherited.
Declaring a class as final implicitly declares all of its methods as final.
30.
UNIT-II 30
Base classObject :
Object class contains the following methods:
Object clone( )
boolean equals(Object object)
void finalize( )
Class getClass( )
int hashCode( )
void notify( )
void notifyAll( )
String toString( )
void wait( )
void wait(long milliseconds)
void wait(long milliseconds, int nanoseconds)
Object is superclass of all other classes.
31.
UNIT-II
Method Purpose
Object clone() Creates a new object that is the same as the object
being cloned.
boolean equals(Object object) Determines whether one object is equal to
another.
void finalize( ) Called before an unused object is recycled.
Class getClass( ) Obtains the class of an object at run time.
int hashCode( ) Returns the hash code associated with the invoking
object.
void notify( ) Resumes execution of a thread waiting on the
invoking object.
void notifyAll( ) Resumes execution of all threads waiting on the
invoking object.
String toString( ) Returns a string that describes the object.
void wait( )
void wait(long milliseconds)
void wait(long milliseconds, int nanoseconds) Waits on another thread of
exec
32.
UNIT-II 32
Subclass, Subtypeand Substitutability:
When new classes are constructed using inheritance from existing
classes, the argument used to justify the validity of substitutability is
as follows:
• Instances of the subclass must possess all data fields associated with
the parent class
• Instances of the subclass must implement, through inheritance atleast
all functionality defined for the parent class.
• An instance of a child class can mimic the behavior of the parent class
and should be indistinguishable from an instance of the parent class if
substituted in a similar situation.
33.
UNIT-II 33
Subclass, Subtypeand Substitutability:
The term subtype is used to describe the relationship between types
that explicitly recognizes the principle of substitution.
Type B is considered to be a subtype of A if two conditions hold
•An instance of B can legally be assigned to a variable declared as type
A.
•This value can then be used by the variable with no observable change
in
behavior.
The term subclass refers to the mechanism of constructing a new
class using inheritance.
34.
UNIT-II 34
Interfaces:
Interfaces aresimilar to classes, but they lack instance variables and their
methods are declared without any body.
The general form of an interface is:
access interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1=value;
type final-varname2=value;
// …
return-type method-nameN(parameter-list);
type final-varnameN=value;
}
Using interface, we can specify what a class must do, but not how it does it.
An interface is defined like a class using the keyword interface.
35.
UNIT-II 35
Interfaces:
Variables declaredinside an interface are implicitly final and static.
interface A
{
int i=10;
void firstMethod( );
}
Example1: Interface
All methods and variables are implicitly public if the interface is declared
as public.
36.
UNIT-II 36
Implementing Interfaces:
Themethods that implement an interface must be declared public.
One (or) more classes can implement an interface.
To implement an interface, include the implements clause in a class definition
and create the methods contained by the interface.
The general form of a class with implements clause is:
class classname [extends superclass] [implements interface1[,interface2...]]
{
//class body
}
37.
UNIT-II 37
Example2: ImplementingInterfaces
interface A
{
int i=10;
void firstMethod();
}
class P implements A
{
public void firstMethod( )
{
System.out.println("This is firstMethod");
}
void display( )
{
System.out.println("This is display");
}
}
class InterfaceDemo1
{
public static void main(String args[ ])
{
P p1=new P();
p1.firstMethod();
}
}
O/P:
This is firstMethod
38.
UNIT-II 38
Example3: AccessingImplementations Through Interface
References
class InterfaceDemo2
{
public static void main(String args[ ])
{
P p1=new P( );
A a1;
a1=p1;
a1.firstMethod();
}
}
O/P:
This is firstMethod
interface A
{
int i=10;
void firstMethod();
}
class P implements A
{
public void firstMethod( )
{
System.out.println("This is firstMethod");
}
void display( )
{
System.out.println("This is display");
}
}
39.
UNIT-II 39
Extending Interfaces:
Oneinterface can inherit another by use of the keyword extends.
The syntax is:
interface interface-name2 extends interface-name1
{
// variables and methods
}
40.
UNIT-II 40
Example4: ExtendingInterfaces
interface InterOne {
void firstMethod( );
void secondMethod( );
}
interface InterTwo extends InterOne {
void thirdMethod( );
void fourthMethod( );
}
class InterfaceDemo2 {
public static void main(String args[ ]) {
Test t1=new Test( );
t1.firstMethod( );
t1.secondMethod( );
t1.thirdMethod( );
t1.fourthMethod( );
}
}
class Test implements InterTwo {
public void firstMethod( ) {
System.out.println("firstMethod");
}
public void secondMethod( ) {
System.out.println("secondMethod");
}
public void thirdMethod( ) {
System.out.println("thirdMethod");
}
public void fourthMethod( ) {
System.out.println("fourthMethod");
}
void display( ) {
System.out.println("This is display");
}
}
41.
UNIT-II 41
Java file:
AJava source file can contain any (or) all of the following four internal parts:
• A single package statement ( optional )
• Any number of import statements ( optional )
• A single public class declaration
• Any number of classes private to the package ( optional )
42.
UNIT-II 42
Packages:
Packages arecontainers for classes.
Packages are stored in a hierarchical manner.
Packages are explicitly imported into class definitions.
43.
UNIT-II 43
Creating aPackage:
Java uses file system directories to store packages.
The .class files for any classes to be part of a package must be stored in a
directory with the same name of the package.
The directory name must match the package name.
Steps for creating user-defined packages:
1. Select a name for the package.
2. Create a directory with the package name.
3. Write the Java source file with the required classes which are to be a
part of the package. The first statement in the Java source file must be
the package statement and the syntax is:
package pack-name;
4. Compile the Java source file such that the .class files are stored in the
package directory.
UNIT-II 45
Access specifiers:
PrivateNo modifier Protected Public
Same class
Same package
subclass
Same package
non-subclass
Different package
subclass
Different package
non-subclass
Yes Yes Yes Yes
Yes Yes Yes
Yes
Yes
Yes
Yes
Yes
Yes
No
No
No
No
No
No No
46.
UNIT-II 46
Example: Createa package
Create a package with three classes Arithmetic, Bitwise and Logical.
Arithmetic class containing methods to perform arithmetic operations.
Similarly Bitwise and Logical classes.
Let the two classes Arithmetic and Bitwise be public and Logical be without
any access specifier.
Declare some of the methods of Arithmetic class to public and other to
private.
Declare some methods of Bitwise class to protected and other without
access specifier.
Declare the methods of Logical class each with one access specifier.
Now write two java applications using the methods of classes in the
above package.
One program outside the package and the other in the same package.
47.
UNIT-II 47
package pack1;
publicclass Arithmetic {
public int add(int a,int b) {
return a+b;
}
public int sub(int a,int b) {
return a-b;
}
public int mul(int a,int b) {
return a*b;
}
private int div(int a,int b) {
return a/b;
}
private int mod(int a,int b) {
return a%b;
}
}
Arithmetic class:
48.
UNIT-II 48
Bitwise class:
packagepack1;
public class Bitwise {
protected int and(int a,int b) {
return a&b;
}
protected int or(int a,int b) {
return a|b;
}
protected int not(int a) {
return ~a;
}
int xor(int a,int b) {
return a^b;
}
int rightShift(int a,int b) {
return a>>b;
}
}
UNIT-II 50
Hierarchy ofpackages:
A package can contain sub packages in it.
The general form is:
package pkg1[.pkg2[.pkg3]];
51.
UNIT-II 51
static import:
Thegeneral form is:
import static packagename.classname.staticmembername;
import static packagename.classname.*;
Enable to refer to imported static members as if they were declared in the class
that uses them.
52.
UNIT-II 52
Forms ofInheritance:
Inheritance is employed in a variety of ways.
The various forms of inheritance:
Inheritance for Specialization
Inheritance for Specification
Inheritance for Construction
Inheritance for Extension
Inheritance for Limitation
Inheritance for Combination
53.
UNIT-II 53
Forms ofInheritance:
Inheritance for Specialization: The child is special case of the parent
class.
Inheritance for Specification: The parent class defines behavior that is
implemented in the child class but not in the parent class.
Inheritance for Construction: The child class makes use of the behavior
provided by the parent class but is not a subtype of the parent class.
Inheritance for Extension: The child class adds new functionality to the
parent class, but does not change any inherited behavior.
Inheritance for Limitation: The child class restricts the use of some of the
behavior inherited from the parent class.
Inheritance for Combination: The child class inherits features from more
than one parent class.
54.
UNIT-II 54
Benefits ofInheritance:
Some of the important benefits of inheritance:
Software Reusability
Increased Reliability
Code Sharing
Consistency of Interface
Software Components
Rapid Prototyping
Polymorphism and Frameworks
Information Hiding
55.
UNIT-II 55
Costs ofInheritance:
Although the benefits of inheritance are great, almost nothing is without
cost of one sort or another.
Some of the costs of inheritance are:
Execution Speed
Program Size
Message-Passing Overhead
Program Complexity
File:
The File classdoes not specify how information is retrieved from or
stored in files; it describes the properties of a file itself.
A File object is used to obtain or manipulate the information associated
with a disk file, such as the permissions, time, date, and directory path,
and to navigate subdirectory hierarchies.
A directory in Java is treated simply as a File with one additional
property—a list of filenames that can be examined by the list( ) method.
The following constructors can be used to create File objects:
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
59
UNIT-II
In Java, inputand output is defined in terms of an abstract concept
called "stream".
A stream is a sequence of data.
If it is an input stream, it has source.
If it is an output stream, it has a destination.
There are two kinds of streams:
byte streams
character streams
The java.io package provides a large number of classes to perform
stream I/O.
The Java I/O Streams:
61
UNIT-II
62.
Byte streams andCharacter streams:
Java’s stream-based I/O is built upon four abstract classes:
InputStream
OutputStream
Reader
Writer
InputStream and OutputStream are designed for byte streams.
Reader and Writer are designed for character streams.
62
UNIT-II
int available( )
voidclose( )
void mark(int readlimit)
boolean markSupported( )
abstract int read( )
int read(byte[ ] b)
int read(byte[ ] b, int off, int len)
void reset( )
long skip(long n)
Methods of InputStream class:
68
UNIT-II
69.
Class FileInputStream:
A FileInputStreamobtains input bytes from a file in a file system.
Constructors:
FileInputStream(File file)
FileInputStream(String name)
int available( )
void close( )
protected void finalize( )
int read( )
int read(byte[ ] b)
int read(byte[ ] b, int off, int len)
long skip(long n)
Some methods:
69
UNIT-II
70.
import java.io.*;
class FileInputStreamDemo
{
publicstatic void main(String args[ ]) throws IOException
{
FileInputStream f1=new FileInputStream("Sample.java");
int a=f1.available( );
System.out.println("Total Available bytes:"+a);
for(int i=1;i<=a;i++)
System.out.print((char)f1.read( ));
f1.close( );
FileInputStream f2=new FileInputStream("Sample.java");
byte b[ ]=new byte[20];
int x=f2.read(b);
for(int i=0;i<b.length;i++)
System.out.print((char)b[i]);
f2.close( );
}
}
FileInputStream: Example program
70
UNIT-II
Class ByteArrayInputStream:
A ByteArrayInputStreamcontains an internal buffer(byte array) that
contains bytes that may be read from the stream.
Constructors:
ByteArrayInputStream(byte array[ ])
ByteArrayInputStream(byte array[ ], int start, int numBytes)
int available( )
void close( )
void mark(int readAheadLimit)
boolean markSupported( )
int read( )
int read(byte[ ] b, int off, int len)
void reset( )
long skip(long n)
Some methods:
72
UNIT-II
73.
import java.io.*;
class ByteArrayInputStreamDemo
{
publicstatic void main(String args[ ]) throws IOException
{
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[ ] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0,3);
int c;
while ((c = input1.read( )) != -1)
{
System.out.print((char) c);
}
while ((c = input2.read( )) != -1)
{
System.out.print((char) c);
}
}
}
ByteArrayInputStream: Example Program
73
UNIT-II
74.
Filtered Byte Streams:
Thisclass is the superclass of all classes that filter input streams.
These streams sit on top of an already existing input stream
(the underlying input stream), but provide additional functionality.
The class FilterInputStream itself simply overrides all methods of
InputStream with versions that pass all requests to the underlying
input stream.
Subclasses of FilterInputStream may further override some of these
methods as well as provide additional methods and fields.
74
UNIT-II
75.
BufferedInputStream:
The class implementsa buffered input stream.
By setting up such an input stream, an application can read bytes from a
stream without necessarily causing a call to the underlying system for each
byte read.
The data is read by blocks into a buffer; subsequent reads can access
the data directly from the buffer.
Constructors:
BufferedInputStream(InputStream inputStream)
BufferedInputStream(InputStream inputStream, int bufSize)
BufferedInputStream also supports the mark( ) and reset( ) methods.
75
UNIT-II
76.
BufferedInputStream: Example Program
importjava.io.*;
class BufferedInputStreamDemo
{
public static void main(String args[]) throws IOException
{
String s = "THIS ON BUFFEREDINPUTSTREAM CLASS";
byte buf[ ] = s.getBytes( );
ByteArrayInputStream in = new ByteArrayInputStream(buf);
BufferedInputStream f = new BufferedInputStream(in);
boolean m=f.markSupported( );
System.out.println("Mark:"+m);
}
}
76
UNIT-II
77.
PushbackInputStream:
This class isan input stream filter that provides a buffer into which data
can be "unread."
An application may unread data at any time by pushing it back into the buffer.
Constructors:
PushbackInputStream(InputStream inputStream)
PushbackInputStream(InputStream inputStream, int numBytes)
PushbackInputStream provides
void unread(int ch)
void unread(byte buffer[ ])
void unread(byte buffer, int offset, int numChars)
77
UNIT-II
78.
PushbackInputStream: Example Program
78
UNIT-II
importjava.io.*;
class PushbackDemo
{
public static void main(String args[]) throws IOException
{
byte b[ ]={65,66,67,68,69,70,71,72,73,74,75,76,77,78};
ByteArrayInputStream bs1=new ByteArrayInputStream(b);
PushbackInputStream p1=new PushbackInputStream(bs1);
System.out.println("Total Available bytes in p1:"+p1.available( ));
int ch=p1.read( );
System.out.println((char)ch);
ch=p1.read( );
System.out.println((char)ch);
p1.unread(ch);
ch=p1.read( );
System.out.println((char)ch);
p1.close( );
}
}
79.
SequenceInputStream:
The sequence inputstream class allows an application to combine
several input streams serially and make them appear as if they
were a single input stream.
Constructors:
SequenceInputStream(InputStream first, InputStream second)
SequenceInputStream(Enumeration streamEnum)
79
UNIT-II
80.
SequenceInputStream: Example Program
importjava.io.*;
class SequenceStreamsDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream f2=new FileInputStream("Sample.java");
byte buf[ ]={65,66,67,68,69,70,71,72,73,74,75,76,77,78};
ByteArrayInputStream bs2=new ByteArrayInputStream(buf);
SequenceInputStream s1=new SequenceInputStream(f2,bs2);
System.out.println("Total Available bytes in s1:"+s1.available( ));
for(int i=1;i<=160;i++)
System.out.print((char)s1.read( ));
}
}
80
UNIT-II
81.
The PrintStream classprovides all of the formatting capabilities we have
been using from the System file handle, System.out.
Constructors:
PrintStream(OutputStream outputStream)
PrintStream(OutputStream outputStream, boolean flushOnNewline)
Java’s PrintStream objects support the print( ) and println( ) methods
for all types, including Object.
If an argument is not a simple type, the PrintStream methods will call the
object’s toString( ) method and then print the result.
PrintStream:
81
UNIT-II
void close( )
voidflush( )
void write(byte[ ] b)
void write(byte[ ] b, int off, int len)
abstract void write(int b).
Methods of OutputStream class:
83
UNIT-II
84.
A file outputstream is an output stream for writing bytes to a file.
FileOutputStream:
Constructors:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)
84
UNIT-II
ByteArrayOutputStream:
ByteArrayOutputStream is animplementation of an output stream
that uses a byte array as the destination.
Constructors:
ByteArrayOutputStream( )
ByteArrayOutputStream(int numBytes)
In the first form, a buffer of 32 bytes is created.
In the second, a buffer is created with a size equal to that specified by
numBytes.
The buffer is held in the protected buf field of ByteArrayOutputStream.
The buffer size will be increased automatically, if needed.
The data can be retrieved using toByteArray( ) and toString( ).
86
UNIT-II
87.
import java.io.*;
class ByteArrayOutputStreamDemo
{
publicstatic void main(String args[]) throws IOException
{
ByteArrayOutputStream bs1 = new ByteArrayOutputStream( );
String s = "This should end up in the array";
byte buf[ ] = s.getBytes( );
bs1.write(buf);
System.out.println("Buffer as a string");
System.out.println(bs1.toString( ));
bs1.close( );
}
}
ByteArrayOutputStream: Example program
87
UNIT-II
88.
The class implementsa buffered output stream.
By setting up such an output stream, an application can write bytes to the
underlying output stream without necessarily causing a call to the
underlying system for each byte written.
The data is written into a buffer, and then written to the underlying stream
if the buffer reaches its capacity, the buffer output stream is closed,
or the buffer output stream is explicity flushed.
BufferedOutputStream:
Constructors:
BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int bufSize)
88
UNIT-II
abstract void close()
abstract void flush( )
void write(char[ ] cbuf)
abstract void write(char[ ] cbuf, int off, int len)
void write(int c)
void write(String str)
void write(String str, int off, int len)
Writer class:
92
UNIT-II
93.
Serialization:
Serialization is theprocess of saving an object in a storage medium
(such as a file, or a memory buffer) or to transmit it over a network connection
in binary form.
The serialized objects are JVM independent and can be re-serialized
by any JVM.
In this case the "in memory" java objects state are converted into a
byte stream.
This type of the file can not be understood by the user.
This process of serializing an object is also called deflating or
marshalling an object.
93
UNIT-II
94.
Serialization:
Some of theclasses and interfaces related to serialization.
Interfaces:
Serializable
ObjectOutput (extends DataOutput)
DataOutput
ObjectInput (extends DataInput)
DataInput
Classes:
ObjectOutputStream(extends OutputStream implements ObjectOutput)
ObjectInputStream (extends InputStream implements ObjectInput)
94
UNIT-II