0% found this document useful (0 votes)
6 views66 pages

JP Unit-Ii

Oops through java

Uploaded by

vaddivanisri1802
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)
6 views66 pages

JP Unit-Ii

Oops through java

Uploaded by

vaddivanisri1802
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/ 66

Java Programming

II B Tech II-Sem CSE


Unit-II

UNIT-II 1
UNIT-II 2
Interfaces:
Interfaces are similar to classes, but they lack instance variables and their
methods are declared without any body.

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.

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;
} UNIT-II 3
Interfaces:

Variables declared inside an interface are implicitly final and static.

All methods and variables are implicitly public if the interface is declared
as public.

Example1: Interface

interface A
{
int i=10;
void firstMethod( );
}

UNIT-II 4
Implementing Interfaces:

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
}

The methods that implement an interface must be declared public.

UNIT-II 5
Example2: Implementing Interfaces
interface A class InterfaceDemo1
{ {
int i=10; public static void main(String args[ ])
void firstMethod(); {
} P p1=new P();
class P implements A p1.firstMethod();
{ }
public void firstMethod( ) }
{
System.out.println("This is firstMethod");
}
void display( )
{ O/P:
System.out.println("This is display");
} This is firstMethod
}

UNIT-II 6
Example3: Accessing Implementations Through Interface
References

interface A class InterfaceDemo2


{ {
int i=10; public static void main(String args[ ])
void firstMethod(); {
} P p1=new P( );
class P implements A A a1;
{ a1=p1;
public void firstMethod( ) a1.firstMethod();
{ }
System.out.println("This is firstMethod"); }
}
void display( )
{
O/P:
System.out.println("This is display");
} This is firstMethod
}

UNIT-II 7
Extending Interfaces:

One interface can inherit another by use of the keyword extends.

The syntax is:

interface interface-name2 extends interface-name1


{
// variables and methods
}

UNIT-II 8
Example4: Extending Interfaces
class Test implements InterTwo {
interface InterOne {
public void firstMethod( ) {
void firstMethod( );
System.out.println("firstMethod");
void secondMethod( );
}
}
public void secondMethod( ) {
System.out.println("secondMethod");
interface InterTwo extends InterOne {
}
void thirdMethod( );
public void thirdMethod( ) {
void fourthMethod( );
System.out.println("thirdMethod");
}
}
public void fourthMethod( ) {
System.out.println("fourthMethod");
class InterfaceDemo2 { }
public static void main(String args[ ]) { void display( ) {
Test t1=new Test( ); System.out.println("This is display");
t1.firstMethod( ); }
t1.secondMethod( ); }
t1.thirdMethod( );
t1.fourthMethod( );
}
} UNIT-II 9
Java file:

A Java 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 )

UNIT-II 10
Packages:
Packages are containers for classes.

Packages are stored in a hierarchical manner.

Packages are explicitly imported into class definitions.

UNIT-II 11
Creating a Package:

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 12
Access specifiers:

Private No modifier Protected Public


Same class Yes Yes Yes Yes
Same package Yes Yes
No Yes
subclass
Same package No Yes Yes Yes
non-subclass
Different package No No Yes Yes
subclass
Different package
No No No Yes
non-subclass

UNIT-II 13
Example: Create a 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.
UNIT-II 14
Arithmetic class:
package pack1;
public class 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;
}
}
UNIT-II 15
Bitwise class:
package pack1;
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 16
Logical class:
package pack1;
class Logical {
public boolean shortAnd(boolean x, boolean y) {
return x&&y;
}
private boolean shortOr(boolean x, boolean y) {
return x||y;
}
protected boolean not(boolean x) {
return !x;
}
boolean xor(boolean x, boolean y) {
return x^y;
}
}

UNIT-II 17
Hierarchy of packages:

A package can contain sub packages in it.

The general form is:

package pkg1[.pkg2[.pkg3]];

UNIT-II 18
static import:

Enable to refer to imported static members as if they were declared in the class
that uses them.

The general form is:


import static packagename.classname.staticmembername;
import static packagename.classname.*;

UNIT-II 19
Forms of Inheritance:

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

UNIT-II 20
Forms of Inheritance:

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.

UNIT-II 21
Benefits of Inheritance:

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

UNIT-II 22
Costs of Inheritance:
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

UNIT-II 23
UNIT-II 24
The Java I/O Classes and Interfaces:

UNIT-II 25
The Java I/O Classes and Interfaces:

UNIT-II 26
File:
The File class does 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)

UNIT-II 27
Some methods in File class:

boolean canRead( ) int hashCode( )


boolean canWrite( ) boolean isDirectory( )
int compareTo(File pathname) boolean isFile( )
boolean createNewFile( ) boolean isHidden( )
boolean delete( ) long lastModified( )
void deleteOnExit( ) long length( )
boolean equals(Object obj) String[ ] list( )
boolean exists( ) File[ ] listFiles( )
String getName( ) boolean mkdir( )
String getParent( ) boolean renameTo(File dest)
File getParentFile( ) boolean setLastModified(long time)
String getPath( ) boolean setReadOnly( )
String toString( )

UNIT-II 28
File: Program 01
import java.io.*;
class File01
{
public static void main(String[] args)
{
File f1 = new File("d1.txt");
System.out.println("File Name: " + f1.getName( ));
System.out.println("Path: " + f1.getPath( ));
System.out.println("Abs Path: " + f1.getAbsolutePath( ));
System.out.println("Length: " + f1.length( ));
System.out.println("IsFile: " + f1.isFile( ));
System.out.println("Exists: " + f1.exists( ));
}
} Output:
File Name: d1.txt
Path: d1.txt
Abs Path: D:\GDR\Java 2021-22\Programs\IO\d1.txt
Length: 106
IsFile: true
UNIT-II 29
Exists: true
File: Program 02

import java.io.*;
class File02
{ Output:
public static void main(String[ ] args)
File Name: Programs
{
Path: D:\Java\Programs
File f1 = new File("D:/Java/Programs"); IsDir: true
System.out.println("File Name: " + f1.getName( )); Files in the Directory
System.out.println("Path: " + f1.getPath( )); AbstractClass.java
System.out.println("IsDir: " + f1.isDirectory( )); AbstractClass2.java
String s[ ]=f1.list(); AbstractClass3.java
System.out.println("Files in the Directory"); AdapterDemo.java
for(int i=0;i<s.length;i++) AdapterKeyDemo.java
System.out.println(s[i]); AdapterMouseDemo.java
Arith.java
}
Arithmetic.java
} Arithmetic1.java
Banner.java
Bitwise.java

UNIT-II 30
The Java I/O Streams:
In Java, input and 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.

UNIT-II 31
Byte streams and Character 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.

UNIT-II 32
The Java I/O Classes and Interfaces:

UNIT-II 33
InputStream class:

UNIT-II 34
OutputStream class:

UNIT-II 35
Reader class:

UNIT-II 36
Writer class:

UNIT-II 37
InputStream class:

UNIT-II 38
Methods of InputStream class:

int available( )
void close( )
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)

UNIT-II 39
Class FileInputStream:

A FileInputStream obtains input bytes from a file in a file system.

Constructors:
FileInputStream(File file)
FileInputStream(String name)

Some methods:

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)

UNIT-II 40
FileInputStream: Example program
import java.io.*;
class FileInputStreamDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream f1=new FileInputStream("abc.txt");
int a=f1.available();
System.out.println("Total Available bytes:"+a);
for(int i=1;i<=10;i++)
System.out.print(" "+f1.read());
a=f1.available();
System.out.println("\nTotal Available bytes:"+a);
f1.close();
FileInputStream f2=new FileInputStream("abc.txt");
byte b[]=new byte[20]; Output:
int x=f2.read(b,3,8); Total Available bytes:52
System.out.println("Byte array:"); 65 66 67 68 69 70 71 72 73 74
for(int i=0;i<20;i++) Total Available bytes:42
System.out.print(" "+b[i]); Byte array:
f2.close(); 0 0 0 65 66 67 68 69 70 71 72 0 0 0 0 0 0 0 0 0
}
UNIT-II 41
}
Class ByteArrayInputStream:
A ByteArrayInputStream contains 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)

Some methods:
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)
UNIT-II 42
ByteArrayInputStream: Example Program
import java.io.*;
class ByteArrayInputStreamDemo
{
public static 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); Output:
} abcdefghijklmnopqrstuvwxyz
while ((c = input2.read( )) != -1) abc
{
System.out.print((char) c);
}
}
UNIT-II 43
}
Filtered Byte Streams:

This class 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.

UNIT-II 44
BufferedInputStream:

The class implements a 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.

UNIT-II 45
BufferedInputStream: Example Program

import java.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);
}
}

UNIT-II 46
PushbackInputStream:

This class is an 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)

UNIT-II 47
PushbackInputStream: Example Program
import java.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( );
}
} UNIT-II 48
SequenceInputStream:

The sequence input stream 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)

UNIT-II 49
SequenceInputStream: Example Program

import java.io.*;
class SequenceStreamsDemo
{
public static void main(String args[]) throws IOException
{
FileInputStream f2=new FileInputStream(“xyz.txt");
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<=20;i++)
System.out.print((char)s1.read( ));
} Output:
}
Total Available bytes in s1:15
JavaProgrammingABCDE

UNIT-II 50
OutputStream class:

UNIT-II 51
Methods of OutputStream class:

void close( )
void flush( )
void write(byte[ ] b)
void write(byte[ ] b, int off, int len)
abstract void write(int b).

UNIT-II 52
FileOutputStream:

A file output stream is an output stream for writing bytes to a file.

Constructors:
FileOutputStream(String filePath)
FileOutputStream(File fileObj)
FileOutputStream(String filePath, boolean append)
FileOutputStream(File fileObj, boolean append)

UNIT-II 53
FileOutputStream: Example program

import java.io.*;
class FileOutputStreamDemo
{
public static void main(String args[]) throws IOException
{
FileOutputStream f1=new FileOutputStream("Sample.java");
byte b[ ]={65,66,67,68,69,70,71,72,73,74,75,76,77,78};
f1.write(65);
f1.write(b);
f1.close();
FileOutputStream f2=new FileOutputStream("Sample.java",true);
f2.write(65);
f2.write(b);
f2.close();
}
}

UNIT-II 54
ByteArrayOutputStream:
ByteArrayOutputStream is an implementation 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( ).

UNIT-II 55
ByteArrayOutputStream: Example program

import java.io.*;
class ByteArrayOutputStreamDemo
{
public static 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( );
}
}

UNIT-II 56
BufferedOutputStream:

The class implements a 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.

Constructors:
BufferedOutputStream(OutputStream outputStream)
BufferedOutputStream(OutputStream outputStream, int bufSize)

UNIT-II 57
PrintStream:

The PrintStream class provides 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.

UNIT-II 58
Reader class:

UNIT-II 59
Reader class:

abstract void close( )


void mark(int readAheadLimit)
boolean markSupported( )
int read( )
int read(char[ ] cbuf)
abstract int read(char[ ] cbuf, int off, int len)
boolean ready( )
void reset( )
long skip(long n)

UNIT-II 60
Writer class:

UNIT-II 61
Writer class:

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)

UNIT-II 62
Serialization:
Serialization is the process 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.

UNIT-II 63
Serialization:
Some of the classes 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)

UNIT-II 64
ObjectInputStream:
ObjectOutputStream:

UNIT-II 65
Serialization: Example Program
import java.io.*;
class SerializationDemo{
public static void main(String args[]) throws IOException {
Sample s1=new Sample( );
System.out.println(""+s1);
s1.a=10; s1.b=20; s1.c=30; s1.d=40;
FileOutputStream f1=new FileOutputStream(“abc.txt");
ObjectOutputStream o1=new ObjectOutputStream(f1);
o1.writeObject(s1);
o1.flush( );
o1.close( );

FileInputStream f2=new FileInputStream(" abc.txt ");


ObjectInputStream o2=new ObjectInputStream(f2);
Sample s2=(Sample)o2.readObject();
o2.close();
System.out.println(""+s2);
}}
class Sample implements Serializable{
int a,b,c,d;
public String toString( ) {
return "This is object of sample class";
UNIT-II 66
}}

You might also like